繁体   English   中英

用DRF反向过滤Django模型

[英]Reverse Filter Django Model with DRF

我在django-models有问题过滤,我使用django-rest-framework来处理这个序列化数据。

我想要的是让所有的畜群都记录动物可能有动物species_type='Cow'或空群的动物。

这是我的模特。

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/ i时,我得到了所有畜群与动物或空畜群的结果。 但是一些牛群中的动物没有过滤species_type='Cow'它仍然会返回属于该群体的所有动物,无论species_type是山羊,绵羊等。

您可以species_type Herd的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))
  1. annotate用于向结果添加额外的字段,因此新的字段animalCount用于保存该组的动物数量。
  2. Q用于构建复杂的查询条件,因此对于这种情况, Q(animals__species_type='Cow')|Q(animalCount=0)表示,通过种群类型为“Cow”的群体中的动物进行过滤,或者没有动物在那群中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM