美文网首页
Django笔记

Django笔记

作者: 大明白 | 来源:发表于2017-01-20 13:38 被阅读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']
    

    相关文章

      网友评论

          本文标题:Django笔记

          本文链接:https://www.haomeiwen.com/subject/hdiwbttx.html