Skip to content

related Field has invalid lookup: icontains

tulpar edited this page Apr 13, 2015 · 1 revision

Date: 2014-09-07
Title: related Field has invalid lookup: icontains 解决方法
Tags: Django
Category: It

这种错误常见于:

1. 后台查询部分,如:
# 有一个表Category是表Article的category外键,Category有属性叫name,
class ArticleAdmin(admin.ModelAdmin):

    """
    A simple AdminModel for Article.
    """
    search_fields = ('title', 'category')

以上情况下肯定会报一个related Field has invalid lookup: icontains错误

2. 你在其他地方写了查询语句,如以下函数:
@classmethod
    def get_articles(cls, CATEGORY=None, TAG=None, NUM=100):
        """
        A simple classmethod.
        Use Article.get_articles(CATEGORY=None, TAG=None, NUM=100) to get articles list.
        """
        if CATEGORY:
            article_list = cls.objects.filter(
                Q(status=0) & Q(category__icontains=CATEGORY))[:NUM]
            return article_list
        return cls.objects.filter(status=0)[:NUM]

如上第二个Q查询里。

以上两种情况原因都是一样的:设置搜索范围,如果有外键,要注明外键的哪个字段,双下划线。

class ArticleAdmin(admin.ModelAdmin):

    """
    A simple AdminModel for Article.
    """
    search_fields = ('title', 'category__name')
@classmethod
    def get_articles(cls, CATEGORY=None, TAG=None, NUM=100):
        """
        A simple classmethod.
        Use Article.get_articles(CATEGORY=None, TAG=None, NUM=100) to get articles list.
        """
        if CATEGORY:
            article_list = cls.objects.filter(
                Q(status=0) & Q(category__name__icontains=CATEGORY))[:NUM]
            return article_list
        return cls.objects.filter(status=0)[:NUM]
Clone this wiki locally