Home > Blockchain >  How to reverse lookup the foreign key in Django
How to reverse lookup the foreign key in Django

Time:03-14

I have 2 models

class Vendor(models.Model):
    vendor_name = models.CharField(max_length=50)

class Food(models.Model):
    vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE)
    food_title = models.CharField(max_length=50)

I want to search for the vendors based on the vendor_name as well as food_title.

Currently, I am able to get the vendors using this filter:

keyword = "vendor name or food title"    
vendors = Vendor.objects.filter(vendor_name__icontains=keyword)

The above filter will only work for vendor names. But, I want to get the vendors based on the food title as well.

CodePudding user response:

You can filter with a Q object [Django-doc]:

from django.db.models import Q

Vendor.objects.filter(
    Q(vendor_name__icontains=keyword) | Q(food__food_title__icontains=keyword)
)

CodePudding user response:

https://docs.djangoproject.com/en/4.0/topics/db/queries/#complex-lookups-with-q-objects

vendors = Vendor.objects.filter(Q(vendor_name__icontains=keyword) | Q(food_title__icontains=keyword))

But better yet, https://docs.djangoproject.com/en/4.0/ref/contrib/postgres/search/

  • Related