Troubleshooting "Related Field has invalid lookup: icontains"

ExceptionDjango Admin

Exception Problem Overview


I have the following models in 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"

While in the admin.py I have the following:

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"]

But when I try to make a search in the admin page in the ListinoTraduttore table I have the following error:

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']

Exception Solutions


Solution 1 - Exception

Have you tried adding the __fieldname on those Lingua references in the ListinoTraduttoreAdmin search_fields, like:

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

Solution 2 - Exception

This is to (hopefully) simplify the answer.

Don't filter on a ForeignKey field itself!


Change this

search_fields = ['foreignkeyfield']

to this (notice TWO underscores)

search_fields = ['foreignkeyfield__name']

name represents the field-name from the table that we have a ForeignKey relationship with.

Hope this helps

Solution 3 - Exception

Use Django's double underscore convention instead. docs foreignkeyfield__name

Make sure you are not adding any Foreignkey or ManyToManyField to your search_field directly.

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

Solution 4 - Exception

Double underscore needed

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

Solution 5 - Exception

This worked for me.

Search the field of the foreign key using my_related_object__first_attribute:

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

Solution 6 - Exception

This error, mostly occurs when you try to filter using a ForeignKey. I think the error is in the search_filelds. Check it. search_fields = ['traduttore__nome", "linguaDa", "linguaA"]. This two ForeignKey ("linguaDa", "linguaA") are the problem. Remove them. I think this helps.

Solution 7 - Exception

This may not answer the original question, but, every so often I run into a similar invalid lookup error because I accidentally used _set in a lookup, e.g. <model_name>_set instead of just <model_name>.

Basically, I tend to confuse the related_query_name with the default_related_name , which does include _set (also see queries docs and related manager docs).

From the lookups documentation:

>It works backwards, too. Whilst it can be customized, by default you refer to a “reverse” relationship in a lookup using the lowercase name of the model.

(my emphasis)

Confusing thing is that the default related_name (i.e. <model_name>_set) is not the same as the default related_query_name (i.e. <model_name>), but if you set a custom related_name (or default_related_name, via model Meta options), that will also be used as the default related_query_name (as mentioned in the docs).

Solution 8 - Exception

it may be weird

search_fields = ['traduttore__nome']

giving like this , with single quotes will create error.

search_fields = ["traduttore__nome"]

giving with double quotes will fix the issue

foreignkeyfield__lookupfield  - this is the format

Solution 9 - Exception

add in admin.py

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

see the link https://docs.djangoproject.com/en/dev/intro/tutorial02/

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1545895View Question on Stackoverflow
Solution 1 - ExceptionbskinnersfView Answer on Stackoverflow
Solution 2 - ExceptionDrorView Answer on Stackoverflow
Solution 3 - ExceptionKwaw AnnorView Answer on Stackoverflow
Solution 4 - ExceptionAzmolView Answer on Stackoverflow
Solution 5 - ExceptionIbbyView Answer on Stackoverflow
Solution 6 - ExceptionEdem RobinView Answer on Stackoverflow
Solution 7 - ExceptiondjvgView Answer on Stackoverflow
Solution 8 - ExceptionSarath Chandran KView Answer on Stackoverflow
Solution 9 - ExceptionMichele CasariView Answer on Stackoverflow