[英]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))
annotate
用於向結果添加額外的字段,因此新的字段animalCount
用於保存該組的動物數量。 Q
用於構建復雜的查詢條件,因此對於這種情況, Q(animals__species_type='Cow')|Q(animalCount=0)
表示,通過種群類型為“Cow”的群體中的動物進行過濾,或者沒有動物在那群中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.