我在django-models中存在过滤问题,我正在使用django-rest-framework来处理这个序列化数据。
我想要的是得到所有的畜群记录,其中动物可能有一个species_type='Cow'或一个空的畜群(S)。
这是我的模特。
models.py
class Herd(models.Model):
name = models.CharField(max_length=25)
description = models.TextField(max_length=250, null=True)
created_at = models.DateTimeField(auto_now_add=True, editable=False)
updated_at = models.DateTimeField(auto_now=True, editable=False)
class Animal(models.Model):
name = models.CharField(max_length=25)
species_type = models.CharField(max_length=25)
breed = models.CharField(max_length=25)
herd = models.ForeignKey(Herd, related_name='animals', on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True, editable=False)
updated_at = models.DateTimeField(auto_now=True, editable=False)serializers.py
class AnimalSerializer(serializers.ModelSerializer):
class Meta:
model = Animal
fields = [
'name',
'species_type',
'breed'
]
read_only_fields = ['id', 'created_at', 'updated_at']
class HerdSerializer(serializers.ModelSerializer):
animals = AnimalSerializer(many=True, read_only=True)
class Meta:
model = Herd
fields = [
'id',
'name',
'description',
'animals'
]
read_only_fields = ['created_at', 'updated_at']这是我的视图集,它处理所有crud操作。
views.py
class HerdViewset(viewsets.ModelViewSet):
"""
This viewset automatically provides `list`, `create`, `retrieve`,
`update` and `destroy` actions.
"""
queryset = Herd.objects.all()
serializer_class = HerdSerializer现在,当我浏览HerdViewSet端点/api/herd/时,我得到了所有带动物或空畜群的牛群的结果。但有些畜群中的动物没有滤除species_type='Cow',仍然返回属于该群的所有动物,无论species_type是山羊、绵羊等。
发布于 2016-11-22 09:49:00
你可以用species_type从牛群中过滤。因为您已经在外键中定义了related_name。
尝尝这个
from django.db.models import Count, Q
Herd.objects.annotate(animalCount=Count('animals')).filter(Q(animals__species_type='Cow')|Q(animalCount=0))annotate用于在结果中添加一个额外的字段,因此使用一个新的字段animalCount来保存该牧群中的动物数量。Q是用来建立复杂的查询条件的,所以在这种情况下,Q(animals__species_type='Cow')|Q(animalCount=0)是指由牧群中的动物进行“牛”类型的过滤,或者在该群中没有动物。https://stackoverflow.com/questions/40738288
复制相似问题