teconomix teconomix - 1 year ago 110
jQuery Question

django-autocomplete-light - how to return a different field then a models primary key?

I am using django-autocomplete-light

in a form for a model I want to use autocomplete on one of its field. the field is not a foreignkey or something, but just a integer field and for autocomplete I would actually like to use the same model then the form I am filling.

The query set from autocomplete however returns the ID and I want to fill the field "projektnummer".

Any clue how I can setup autocomplete so that it returns not the primary key of the model but some other field?

also it seems that I get a wired failure from crispy forms when I use the autocomplete-widget on the integer field.


class KombiPublikation(models.Model):
typid = models.ForeignKey('KombiPublikationsTypMedium', verbose_name='Outputtyp', db_column='typid') # publikationstyp.id or publikationstypinfo.typid
projektnummer = models.IntegerField(verbose_name='Projektnr.', default=0, blank=True)


class SearchProjectinFormAutocomplete(autocomplete.Select2QuerySetView):
def get_queryset(self):
qs = KombiPublikation.objects.filter(typid__in=[222, 223, 224]).filter(zeigen=1)

if self.q:
qs = qs.filter(Q(projektnummer__contains=self.q))

return qs


class KombiPublikationForm(forms.ModelForm):

class Meta:
model = KombiPublikation
#fields = []
exclude = ['pub_sprache']
widgets = {
'typid': autocomplete.ModelSelect2(url='output:typ-autocomplete', forward=['typtyp']),
'projektnummer': autocomplete.ModelSelect2(url='output:projekt-form-autocomplete'),

Answer Source

I found the answer.

You actually have to override get_result_value from the base autocomplete.Select2QuerySetView to return the variable you want from the resulting object. :)

def get_result_value(self, result):
    """Return the value of a result."""
    return result.pk #change pk to the variable of your choice
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download