简体   繁体   中英

Filter and fetch using select_related and prefetch_related in django

Here are my below models:

class City(models.Model):
    city = models.CharField('city name', max_length=25)

class Pincode(models.Model):
    city = models.ForeignKey(City, on_delete=models.CASCADE, related_name='city_pincode')
    pincode = models.PositiveIntegerField('pincode', unique=True)

class Vendors(models.Model):
    pincode = models.ManyToManyField(Pincode, related_name='pincode_vendor')
    shop_name = models.CharField('Shop name(English)', max_length=50)

class SubCategory(models.Model):    
    category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='category_subcategory')
    vendor = models.ForeignKey(Vendors, on_delete=models.CASCADE, related_name='vendor_subcategory')

class ItemGroup(models.Model):
    name = models.CharField('name', max_length=50, unique=True, blank=True)

class Item(models.Model):
    subcategory = models.ForeignKey(SubCategory, on_delete=models.CASCADE, related_name='subcategory_item')
    itemgroup = models.ForeignKey(ItemGroup, on_delete=models.CASCADE, related_name='itemgroup_item')
    name = models.CharField('name', max_length=255)

I am trying to fetch all the subcategories using fields itemgroup and pincode from models Item and Itemgroup.

Here is my code:

SubCategory.objects.filter(vendor__pincode__pincode=500071).prefetch_related(Prefetch('subcategory_item',
            queryset=Item.objects.filter(itemgroup__name='Biryanis')
        ))

Here is i am getting all the items in the subcategory model. But i want only those subcategories whose itemgroup='Biryanis' and pincode='500071'.

I think you are misunderstanding select_related and prefetch_related . These two methods are used only to gain performance by minimizing database calls.

Your code does not perform filter on the subcategory_item. Use the following code to do so.

SubCategory.objects.filter(vendor__pincode__pincode=500071).filter(subcategory_item__itemgroup__name='Biryanis')

If your question was about performance:

Using select_related and prefetch_related will not benefit you if you are calling the database once. And there are there some disadvantages in using those methods. Make sure you read the QuerySet docs .

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