django-models - 根据为 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 请求用户的产品。
解决方案
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
推荐阅读
- python - Dask - 如何有效地执行正确数量的任务
- html - 有没有办法在链接悬停时设置 html 元素的样式?
- c# - puppeter sharp如何获取一个属性的值?
- raytracing - 内联光线追踪的绑定
- javascript - 纸牌游戏的编程约束
- python - ImportError:无法导入 PIL.Image。使用 `load_img` 需要 PIL。即使在使用枕头库之后
- python - Python3 无法读取或至少找不到文件
- windows - 运行从haskell项目构建的exe文件时停止打开命令提示符
- ml.net - ml.net 使用历史数据预测结果
- python - python 3 - 这种类型的字符串有问题 - >“ss:seconds:3\x01”