Django Grappelli自动完成M2M

时间:2016-09-12 14:56:08

标签: django autocomplete many-to-many django-grappelli

我按照文档进行了跟踪,无法在Grappelli中使用M2M自动完成查找功能。

#models.py
#main model
class Entry(models.Model):
    title = models.CharField(max_length=60)
    content = models.TextField()
    keywords = models.ManyToManyField(Keyword, blank=True)


#model I want to be searched through while typing in the autocomplete field
class Keyword(models.Model):
    name = models.CharField(max_length=30)

    @staticmethod
    def autocomplete_search_field():
        return ('id__iexact', 'name__icontains',)

    def __str__(self):
        return '%s' % (self.name)

然后在admin.py

class EntryAdmin(admin.ModelAdmin):
    raw_id_fields = ('keywords',)
    autocomplete_lookup_fields = {
        'm2m': ['keywords'],
    }

class KeywordAdmin(admin.ModelAdmin):
    pass

admin.site.register(Entry, EntryAdmin)
admin.site.register(Keyword, KeywordAdmin)

图片显示,即使有keyword条名为'财务状况'

,也不会返回任何结果。

Keyword Lookup with Grappelli M2M

1 个答案:

答案 0 :(得分:2)

正确的方法名称是autocomplete_search_fields,复数。在您的关键字模型中,您使用的是autocomplete_search_field