简体   繁体   中英

filter on foreign and many to many relationship field

I'm struggling getting the right query for my project. Here is an example of my model :

from django.db import models

class Brand(models.Model):
    name = models.CharField(max_length=30)
    handle = models.SlugField(max_length=30, unique=True, null=True, blank=True)
    def __unicode__(self):
        return self.name

class Product(models.Model):
    product_id = models.SlugField(unique=True)
    brand = models.ForeignKey(Brand, on_delete=models.SET_NULL, blank=True, null=True)
    collections = models.ManyToManyField('Collection')
    def __unicode__(self):
        return self.product_id

I am trying to get all the Brand_name based on the value of the Product.collection

Eg: Shoes is a Product.collection , I want to get all the Brand_name for collection - shoes

I tried __ method also. Somehow it is not working.

您应该尝试这样的事情:

Brand.objects.product_set.filter(collections__name="Shoes").values('brand__name')
Brand.objects.filter(
    product__collection=product.collection
).values_list('name', flat=True).distinct()

product is instance of Product .

Add a related_name to your foreign key like below,

brand = models.ForeignKey(Brand, on_delete=models.SET_NULL, blank=True, 
                          null=True, related_name='products')

And then you can try below query and it'll return you a list of all the Brand.name which has product__collections_name='Shoes' .

Brand.objects.filter(products__collections__name='Shoes').values_list('name', flat=True)

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