首页 > 解决方案 > 制作一个孩子满足条件的查询集

问题描述

我正在使用 Django Rest Framework 构建一个 API,并且在我的一个端点中,我需要返回满足条件 active = True 的父亲和孩子

这些是我的模型:

class Category(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField(blank=True, null=True)
    active = models.BooleanField(default=True)



class Product(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField(blank=True, null=True)
    category = models.ForeignKey('Category', on_delete=models.CASCADE, related_name='products')
    active = models.BooleanField(default=True)

这是我的查询集:

queryset = Category.objects.filter(products__active=True)

我将序列化程序配置为返回类别及其产品。

我希望响应是具有唯一活动产品的所有类别,但它返回所有具有活动和非活动产品的类别

有什么建议么?

非常感谢

标签: djangodjango-modelsdjango-rest-framework

解决方案


您的查询与 Django 无关,rest framework纯粹是 Django。从您发布的模型中,既Category没有也没有Product字段 name active。如果他们有,请更新您的问题。但假设他们没有,这应该是你的模型:

class Category(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField(blank=True, null=True)
    active = models.BooleanField(default=True) # or False


class Product(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField(blank=True, null=True)
    category = models.ForeignKey('Category', on_delete=models.CASCADE, related_name='products')
    active = models.BooleanField(default=True) # or False

这样,那些处于活动状态的将在您的查询中。

更新:您可以通过这种方式获得有效产品:

 products = Product.objects.filter(active=true)

您可以通过Categories以下方式获得有效产品:

categories = Category.objects.filter(product__active=True)

更新 2:我不太确定您打算如何处理数据,但从评论中,如果您想遍历每个类别的活动产品,方法如下:

for c in categories:
    active_products = Product.objects.filter(active=True, category=c)
    for p in active_products:
        print(p.title) # or anything else you want

推荐阅读