在 Django 中过滤多对多关系

Filtering in a many-to-many relationship in Django

我有三个模型,这里我展示两个:

class Product(models.Model):
    description = models.CharField(max_length=50)
    price = models.IntegerField()
    stock = models.IntegerField()
    def __str__(self):
        return self.description

# Many-to-many relations
class ProductsCategories(models.Model):
    idProduct = models.ForeignKey(Product, on_delete=CASCADE)
    idCategory = models.ForeignKey(Category, on_delete=CASCADE)

如何在 views.py 文件中获取按类别编号 3 过滤的产品? 我有这个:products_list = Product.objects.all()

提前致谢。

您不需要在 Django 中为“第三个”table 创建模型。您可以简单地使用 ManyToManyField,然后使用所需的条件过滤结果:

class Product(models.Model):
    description = models.CharField(max_length=50)
    price = models.IntegerField()
    stock = models.IntegerField()

    categories = models.ManyToManyField(Category)

    def __str__(self):
        return self.description

在 views.py 中您必须过滤结果:

products_list = Product.objects.filter(categories__id=1)