Search code examples
python-3.xdjangodjango-modelsdjango-3.1

Access manyTomany field (Label) from category class via subclass(Products) Category-> Products -> Labels


Here is the code of my models file:

from django.db import models

# Create your models here.

class Category(models.Model):
    name = models.CharField(max_length=255)

    def __str__(self):
        return self.name

class Product(models.Model):
    category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='products')
    name = models.CharField(max_length=255)
    price = models.DecimalField(decimal_places=2, max_digits=9)

    def __str__(self):
        return self.name

class Label(models.Model):
    name = models.CharField(max_length=255)
    products = models.ManyToManyField(Product,  related_name='labels')

    def __str__(self):
        return self.name

Now I want to access manyTomany field i.e. Label from Category please help me

Thanks in advance


Solution

  • You can try like this.

    # first get the single category object 
    category = Category.objects.get(pk=1)
    # querying products in this category 
    products = category.products.all()
    # now filter the Label model based on the category products 
    labels = Label.objects.filter(products__in=products)