Make a queryset in which the children meet a condition

时间:2019-05-31 11:55:24

标签: django django-models django-rest-framework

I am building an API with Django Rest Framework and in one of my endpoints I need to return the father and the children that meet the condition active = True

These are my models:

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)

And this is my queryset:

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

I have the serializer configured to return the categories along with their products.

I would like the response to be all the categories with the only active products but it returns all the categories with the active and inactive products

Any suggestions?

Thank you very much

1 个答案:

答案 0 :(得分:0)

您的查询与rest framework无关,仅是Django。在您发布的模型中,CategoryProduct都没有字段名称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