1👍
You can .filter(…)
[Django-doc] with:
Brand.objects.filter(Products__category=my_category).distinct()
or for a category name:
Brand.objects.filter(
Products__category__category_name=my_category_name
).distinct()
the .distinct()
call [Django-doc]
prevents returning the same Brand
multiple times.
Note: normally the name of the fields in a Django model are written in snake_case, not PascalCase.
Since the value for therelated_name=…
parameter [Django-doc]
specifies the name of a field that will be defined on the target model, the value of therelated_name=…
parameter should be written in snake_case as well, so it should be:products
instead of.Products
Note: Your
Product
model acts as a junction table for a many-to-many relation betweenCategory
andBrand
. You can span a
ManyToManyField
[Django-doc]
on theCategory
model with:class Category(models.Model): # … brands = models.ManyToManyField( Brand, through='Product' )
0👍
Based on your models it should be something like:
brand_names = Product.objects.filter(category__category_name="some_name").values_list("brand_name__brand_name", flat=True)
or if by brand_name you mean Brand model instances then
brand_names = Product.objects.filter(category__category_name="some_name").brand_name.all()
(BTW I would consider renaming fields in your models. In Product model rename brand_name
to just brand
and inside Brand rename field brand_name
to just name
. The same for Category. It will be much less confusing)