django - 制作一个孩子满足条件的查询集
问题描述
我正在使用 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)
我将序列化程序配置为返回类别及其产品。
我希望响应是具有唯一活动产品的所有类别,但它返回所有具有活动和非活动产品的类别
有什么建议么?
非常感谢
解决方案
您的查询与 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
推荐阅读
- php - 如何将年龄字段添加到 woocommerce 编辑帐户
- sql-server - 在 WHERE 子句中使用 IS NOT NULL 时查询性能不佳
- typescript - 如何使用角度6中的输入标签进行下拉
- javascript - 如何使用已创建函数中的信息添加到新函数中
标签
- progressive-web-apps - PWA nuxt 离线资产
- php - 当我在 facebook 上与图像和标题共享时,如何从我的整个页面显示特定的块或 div
- javascript - 单击另一个窗口中的按钮时,使一个窗口中的 div 可见
- sql - 我想比较一列中日期的相等性,该列放在一张表中
- bash - 在命令替换中调用 grep 失败
- javascript - 使用 react-beautiful-dnd 嵌套拖放