Django-autocomplete-light返回对象名称而不是相应的字段值

时间:2016-07-01 11:44:53

标签: python django django-autocomplete-light

我的问题是django-autocomplete-light(dal 3)是在管理员中,而不是显示选择对应tom我的指定字段(即birth_nationforms.py部分),我总是得到我的查询集对象的 str 值列表(请参阅#models.py部分),这实际上是last_name字段。

# models.py

class MyModel(models.Model):
   id_name = models.CharField(primary_key=True, max_length=255)
   first_name = models.CharField(max_length=255, blank=True, null=True)
   middle_name = models.CharField(max_length=255, blank=True, null=True)
   last_name = models.CharField(max_length=255)
   birth_city = models.CharField(max_length=255, blank=True, null=True)
   birth_nation = models.CharField(max_length=255, blank=True, null=True)

   def __str__(self):
       return self.last_name

   class Meta:
       managed = False
       db_table = 'mytable'

# forms.py
class MyModelForm(forms.ModelForm):
    birth_nation = forms.ModelChoiceField(
        queryset=MyModel.objects.all(),
        widget=autocomplete.ModelSelect2(url='country-autocomplete',
                attrs={'data-minimum-input-length': 2}
        )
    )

    class Meta:
        model = MyModel
        fields = ('__all__')


# views.py

class MyModelAutocomplete(autocomplete.Select2QuerySetView):
    def get_queryset(self):
        if not self.request.user.is_authenticated():
            return MyModel.objects.none()

        qs = MyModel.objects.all()

        if self.q:
            qs = qs.filter(birth_nation__istartswith=self.q)
        return qs

显然,我想得到与birth_nation相对应的选择,我的代码有什么问题?

1 个答案:

答案 0 :(得分:0)

试试这个:

def __str__(self):
   return self.birth_nation