I know this question has been answered in different ways but i'm still unable to see the clear picture. I have the following tables with following relationships:
class Category(models.Model):
name = models.CharField(max_length=100, null=False, blank=False)
def __str__(self):
return self.name
class SubCategory(models.Model):
sub_name = models.CharField(max_length=100, null=False, blank=True, default='None')
category = models.ManyToManyField(Category, default=1)
class Product(models.Model):
name = models.CharField(max_length=150, null=False, blank=False)
brand = models.CharField(max_length=100, null=False, blank=False)
price = models.FloatField(null=False, blank=False)
weight = models.CharField(max_length=100,null=False, blank=False)
sub_category = models.ForeignKey(SubCategory, on_delete=models.SET_DEFAULT, default=13)
category = models.ForeignKey(Category, on_delete= models.CASCADE)
I am trying to solve two queries as follows:
NOTE: Each brand can sell products of multiple categories and subcategories.
Let us take it step by step
Product.objects.filter(brand=brand)
Product.objects.filter(brand=brand).values_list("category_id", flat=True)
queryset = Product.objects.filter(brand=brand).values_list("category_id", flat=True)
categories = Category.objects.filter(id__in=queryset)
Note: If you just want to fetch the category names, you can do
Product.objects.filter(brand=brand).values_list("category__name", flat=True).distinct()
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.