首页 > 解决方案 > 根据为 True 的布尔字段过滤查询集结果

问题描述

class User(models.Model):
    name = models.EmailFiled()

class Product(models.Model):
    title = models.CharField(max_length=50)
    is_active = models.BooleanField(default=True)

class Cart(models.Model):
    product = models.ManyToManyField(Product)


class Order(models.Model):
    user = models.ForeignKey(User,on_delete=models.CASCADE)
    cart = models.ForeignKey(Cart,on_delete=models.CASCADE)

我们有多种产品。其中一些是活动的=假,其他的是真。我应该使用 active=true 请求用户的产品。

标签: django-modelsdjango-rest-frameworkdjango-filters

解决方案


You are looking for the ability to filter results of a ViewSet based on your active flag. I highly recommend you to read DRF Filtering documentation

You simply need to add to your ViewSet or APIView the following fields

from django_filters.rest_framework import DjangoFilterBackend

class ProductList(generics.ListAPIView):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer
    # Add Filtering Backend
    filter_backends = [DjangoFilterBackend]
    # Add filtering fields (Default behavior is to exact match provided values)
    filterset_fields = ['is_active']

and now in your request, you should have the query param

http://example.com/api/products?is_active=1

推荐阅读