diff --git a/django_select2/fields.py b/django_select2/fields.py index 4f363110..e735ff48 100644 --- a/django_select2/fields.py +++ b/django_select2/fields.py @@ -158,6 +158,19 @@ def label_from_instance(self, obj): """ return smart_unicode(obj) + def extra_data_from_instance(self, obj): + """ + Sub-classes should override this to generate extra data for values. These are passed to + Javascript and can be used for custom rendering. + + :param obj: The model object. + :type obj: :py:class:`django.model.Model` + + :return: The extra data dictionary. + :rtype: :py:obj:`dict` + """ + return {} + def prepare_qs_params(self, request, search_term, search_fields): """ Prepares queryset parameter to use for searching. @@ -246,7 +259,8 @@ def get_results(self, request, term, page, context): res = list(qs.filter(*params['or'], **params['and'])) has_more = False - res = [(getattr(obj, self.to_field_name), self.label_from_instance(obj), ) for obj in res] + res = [(getattr(obj, self.to_field_name), self.label_from_instance(obj), self.extra_data_from_instance(obj)) + for obj in res] return (NO_ERR_RESP, has_more, res, ) diff --git a/django_select2/views.py b/django_select2/views.py index 1798ed27..3bbbaecc 100644 --- a/django_select2/views.py +++ b/django_select2/views.py @@ -98,8 +98,13 @@ def _results_to_context(self, output): err, has_more, results = output res = [] if err == NO_ERR_RESP: - for id_, text in results: - res.append({'id': id_, 'text': text}) + for result in results: + id_, text = result[:2] + if len(result)>2: + extra_data = result[2] + else: + extra_data = {} + res.append(dict(id=id_, text=text, **extra_data)) return { 'err': err, 'more': has_more,