通过 subclass(Products) Category-> Products -> Labels 从类别 class 访问 manyTomany 字段(Label)

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

这是我的模型文件的代码:

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

现在我想访问 manyTomany 字段,即来自类别的标签 请帮助我

提前致谢

你可以这样试试

# 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)