疑难解答“相关字段的查找无效:​​icontains”


94

我在以下模型中有models.py

class ListinoTraduttore(models.Model):
        traduttore = models.ForeignKey('Traduttore', related_name='Traduttore')
        linguaDa = models.ForeignKey(Lingua, related_name = "linguaDa")
        linguaA = models.ForeignKey(Lingua, related_name = "linguaA")
        prezzoParola = models.CharField(max_length=50, blank=True)
        prezzoRiga = models.CharField(max_length=50, blank=True)
        scontoCat = models.CharField(max_length=50, blank=True)
        scontoFuzzy = models.CharField(max_length=50, blank=True)
        scontoRipetizioni = models.CharField(max_length=50, blank=True)
        class Meta:
                verbose_name_plural = "Listini Traduttori"
        def __unicode__(self):
                return u"%s Da %s A %s Parola=%s Riga=%s ScontoCAT=%s ScontoFuzzy=%s ScontoRipetizioni=%s" % (self.traduttore, self.linguaDa, self.linguaA, self.prezzoParola, self.prezzoRiga, self.scontoCat, self.scontoFuzzy, self.scontoRipetizioni)


class Traduttore(models.Model):
        nome = models.CharField(nomeString, max_length=50)
        cognome = models.CharField(cognomeString, max_length=50)
        nomeAzienda = models.CharField(nomeAziendaString, max_length=50, blank=True)
        codiceFiscale = models.CharField(codiceFiscaleString, max_length=50, blank=True)
        partitaIva = models.CharField(partitaIvaString, max_length=50, blank=True)
        indirizzo = models.CharField(indirizzoString, max_length=50, blank=True)
        telefono = models.CharField(telefonoString, max_length=50, blank=True)
        fax = models.CharField(faxString, max_length=50, blank=True)
        email = models.EmailField(max_length=50, blank=True)
        referente = models.CharField(referenteString, max_length=50, blank=True)
        valuta = models.ForeignKey(Valuta)
        metodoPagamento = models.ForeignKey(MetodoPagamento)
        datiBancari = models.CharField(datiBancariString, max_length=50, blank=True)
        programmiUtilizzati = models.ManyToManyField(Programma, blank=True)
        note = models.CharField(max_length=200, blank=True)
        listino = models.ManyToManyField(ListinoTraduttore, related_name='listino', blank=True)
        def __unicode__(self):
                return u"%s %s %s" % (self.nome, self.cognome, self.nomeAzienda)
        class Meta:
                verbose_name_plural = "Traduttori"

在中时,admin.py我有以下内容:

class TraduttoreAdmin(admin.ModelAdmin):
        list_display = ("nome", "cognome", "nomeAzienda")
        search_fields = ["nome", "cognome", "nomeAzienda"]

class ListinoTraduttoreAdmin(admin.ModelAdmin):
        list_display = ("traduttore", "linguaDa", "linguaA", "prezzoParola", "prezzoRiga", "scontoCat", "scontoFuzzy", "scontoRipetizioni")
        search_fields = ['traduttore__nome", "linguaDa", "linguaA"]

但是,当我尝试在ListinoTraduttore表格的管理页面中进行搜索时,出现以下错误:

TypeError at /admin/itrad/listinotraduttore/
Related Field has invalid lookup: icontains
Request Method: GET
Request URL:    http://127.0.0.1:8000/admin/itrad/listinotraduttore/?q=Fenicio
Django Version: 1.4.1
Exception Type: TypeError
Exception Value:    
Related Field has invalid lookup: icontains
Exception Location: /Library/Python/2.7/site-packages/django/db/models/fields/related.py in get_prep_lookup, line 142
Python Executable:  /usr/bin/python
Python Version: 2.7.2
Python Path:    
['/Users/nicolac/Documents/DjangoProjects/mysite',
 '/Library/Python/2.7/site-packages/pip-1.1-py2.7.egg',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python27.zip',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC',
 '/Library/Python/2.7/site-packages']

Answers:


148

您是否尝试过在search_fields中的__fieldname这些Lingua引用上添加ListinoTraduttoreAdmin,例如:

class ListinoTraduttoreAdmin(admin.ModelAdmin):        
    list_display = ("traduttore", "linguaDa", "linguaA", "prezzoParola", "prezzoRiga", "scontoCat", "scontoFuzzy", "scontoRipetizioni")
    search_fields = ['traduttore__nome", "linguaDa__field1", "linguaA_field2"]

4
这只是一个非常无用的错误消息。就我而言,这基本上是解决方案。参考代码。djangoproject.com
ticket /

5
这对我来说是正确的答案。解决了我在任何FOREIGN KEY上进行搜索时的问题。谢谢
cnobile 2013年

正如@seans所述,这应该是可接受的答案,每次在search_fields(django 1.11)上有一个外键时,都会发生此错误。
Cyrlop

6年后,糟糕的错误消息仍然存在!
rbennell 18/09/28

105

这是(希望)简化答案。

不要过滤ForeignKey字段本身


改变这个

search_fields = ['foreinkeyfield']

到(注意两个下划线)

search_fields = ['foreinkeyfield__name']

name 表示与我们有ForeinKey关系的表中的字段名称。

希望这可以帮助


1
顺便说一句,这是我想要的答案,我也尝试过:search_fields = ['foreinkeyfield__foreinkeyfield__name'],它也有效。谢谢
CK

59

确保您没有将任何Foreignkey或ManyToManyField直接添加到search_field中。

请改用Django的双下划线约定。docs

class ListinoTraduttoreAdmin(admin.ModelAdmin):
    list_display = ("traduttore", "linguaDa", "linguaA", "prezzoParola", "prezzoRiga", "scontoCat", "scontoFuzzy", "scontoRipetizioni")
    search_fields = ['traduttore__nome", "linguaDa__field1", "linguaA__field2"]

13
这是重要的提示!因此,如果要搜索ForeignKey,则应显式地查询那里的属性(例如my_related_object__first_attribute)。
OBu

2

需要双下划线

class exampleAdmin(admin.ModelAdmin):
 search_field = ('yourforeignkeyname__choosefieldnameinyourforeignkey')

注意:需要双下划线
Azmol

0

这对我有用。

使用my_related_object__first_attribute搜索外键的字段:

search_fields = ('author__username', 'title')
from models
author = models.ForeignKey(User, on_delete=models.CASCADE,   related_name='blog_posts2')

0

当您尝试使用ForeignKey进行筛选时,通常会发生此错误。我认为错误是在search_filelds中。检查。search_fields = ['traduttore__nome“,” linguaDa“,” linguaA“]。这两个ForeignKey(” linguaDa“,” linguaA“)是问题,请将其删除。


0

这可能无法回答最初的问题,但是我经常遇到类似的问题 invalid lookup由于我无意中使用_set了查找功能(例如,<model_name>_set而不仅仅是)错误<model_name>

基本上,我倾向于将related_query_namedefault_related_name混淆 ,后者包括_set(请参见query docsrelated manager docs)。

来自 查找文档

它也向后工作。尽管可以自定义,但默认情况下,您使用模型小写名称

(我的重点)

令人困惑的是,默认值 related_name(即<model_name>_set)与默认值 related_query_name(即<model_name>)不同,但是如果您设置了自定义 related_name(或default_related_name通过模型Meta选项),该默认值也将用作默认值related_query_name(如文档中所述)。


-2

添加admin.py

admin.site.register(Traduttore, TraduttoreAdmin)
admin.site.register(ListinoTraduttore, ListinoTraduttoreAdmin)

请参阅链接https://docs.djangoproject.com/en/dev/intro/tutorial02/


嗨,我做到了,但没有任何改变。我有同样的错误。你有什么其他的建议?
user1545895'8

这是行不通的。我们需要访问的是外键字段。可以如下查找。`[foreignfield__name]`
拉班时髦的僧侣
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.