Django笔记

2017-01-20  本文已影响27人  大明白
  1. Related Field has invalid lookup: icontains错误

定义Model时,如果有外键(),在admin中如果指定search_fields时,指定了外键汇报错误

Related Field has invalid lookup: icontains

解决方法是search_fields中指定外键对应类的字段,因为类不能search
比如:

# models.py
class School(models.Model):
    name = models.CharField(max_length=128, verbose_name="名字")

    class Meta:
        verbose_name_plural = "学校"
        verbose_name = "学校"


class Teacher(models.Model):
    name = models.CharField(max_length=128, verbose_name="名字")
    school = models.ForeignKey(School, verbose_name="学校")

    class Meta:
        verbose_name_plural = "老师"
        verbose_name = "老师"

school是外键,指定search_fields时指定了school__name

# admin.py
@admin.register(School)
class SchoolAdmin(admin.ModelAdmin):
    list_display = ['name']
    list_display_links = ['name']
    fields = ['name']
    search_fields = ['name']


@admin.register(Teacher)
class TeacherAdmin(admin.ModelAdmin):
    list_display = ['name', 'school']
    list_display_links = ['name']
    fields = ['name', 'school']
    list_filter = ['school']
    search_fields = ['name', 'school__name']
上一篇下一篇

猜你喜欢

热点阅读