简体   繁体   中英

Django how to search for one Model based on multiple foreign keys?

I'm essentially trying to build a filter based on the model's name and multiple foreign keys.

class Foo(models.Model):
    name = models.Charfield()

class Bar(models.Model):
    name = models.ForeignKey(Foo)

Foo can have the same names, but different Bars.

I want to search for the specific Foo based on Bars.

So far I am able to parse user input and create a list ["foo.name", "bar.name", "bar.name"]

How do I filter the product based on that specific Foo? and with trailing Bars?

# pseudocode process
foo = foo.objects.filter(name__contains=list[0] and foo.objects.filter(bar_name__in=[list]

I think maybe if you give a related_name to the ForeignKey, you should be able to search from Foo using that as the field.

So if you do models.ForeignKey(Foo, related_name="backlink") , then Foo would have a backlink field you could search on.

Have a look here and see if that helps.

https://docs.djangoproject.com/en/4.0/ref/models/fields/#django.db.models.ForeignKey.related_name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM