简体   繁体   中英

Is there a way to query reverse in django models?

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:

  • Fetch all the category and subcategories to a specific category where the brand is given. Display structure that i'm making is Brand(Men->Shirts,Pants etc. Women->Shirts,Pants etc).

NOTE: Each brand can sell products of multiple categories and subcategories.

  • Fetch all the subcategories where the category name must be taken out from the result of Category.objects.all() . Display structure that i'm making here is Men(its sub categories), Women(its sub categories)

Let us take it step by step

  1. Get all products for a specific brand
Product.objects.filter(brand=brand)
  1. Now we want to list down the categories for this match. We'll get the ids of categories instead
Product.objects.filter(brand=brand).values_list("category_id", flat=True)
  1. Now let us get the corresponding category objects
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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM