我想为我的应用程序中的所有模型设置一个 is_active
字段,每当我创建一个 api 时,我只想过滤事件的模型并发送响应。有没有通用的方法来做到这一点?截至目前,我保留了一个 boolean
字段 is_active
并且每次检索对象时,我都在编写一个过滤器。下面是代码:
我的models.py
class Crew(models.Model):
crew_id = models.AutoField(primary_key=True)
crew_code = models.CharField(max_length=200, null=False, unique=True)
crew_name = models.CharField(max_length=200, null=False)
crew_password = models.CharField(max_length=200, null=False)
is_active = models.BooleanField(default=True)
我的views.py
:
@api_view(['GET'])
def get_crews(request):
c = Crew.objects.filter(is_active=True)
serializer = CrewSerializer(c, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
最佳答案
你可以写custom model manager :
class IsActiveManager(models.Manager):
def get_queryset(self):
return super(IsActiveManager, self).get_queryset().filter(is_active=True)
class Crew(models.Model):
...
objects = IsActiveManager()
现在 Crew.objects.all()
将只返回 is_active 记录。
关于python - 按 Django 中的 is_active bool 字段过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44924404/