Troubleshooting “Related Field has invalid lookup: icontains”

后端 未结 8 866
萌比男神i
萌比男神i 2021-01-31 06:33

I have the following models in models.py:

class ListinoTraduttore(models.Model):
        traduttore = models.ForeignKey(\'Traduttore\', related_name=         


        
相关标签:
8条回答
  • 2021-01-31 07:11

    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).

    0 讨论(0)
  • 2021-01-31 07:15

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

    Use Django's double underscore convention instead. docs

    class ListinoTraduttoreAdmin(admin.ModelAdmin):
        list_display = ("traduttore", "linguaDa", "linguaA", "prezzoParola", "prezzoRiga", "scontoCat", "scontoFuzzy", "scontoRipetizioni")
        search_fields = ['traduttore__nome", "linguaDa__field1", "linguaA__field2"]
    
    0 讨论(0)
  • 2021-01-31 07:19

    Double underscore needed

    class exampleAdmin(admin.ModelAdmin):
     search_field = ('yourforeignkeyname__choosefieldnameinyourforeignkey')
    
    0 讨论(0)
  • 2021-01-31 07:22

    This is to (hopefully) simplify the answer.

    Don't filter on a ForeignKey field itself!


    Change this

    search_fields = ['foreinkeyfield']
    

    to (notice TWO underscores)

    search_fields = ['foreinkeyfield__name']
    

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

    Hope this helps

    0 讨论(0)
  • 2021-01-31 07:23

    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')
    
    0 讨论(0)
  • 2021-01-31 07:24

    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/

    0 讨论(0)
提交回复
热议问题