我想在过滤计数中使用django序列化程序列表 (Model< - > Foreign< - > Foreign(Count))
看我的模特
class Test(models.Model):
item = CharField
title = CharField
class TestChild(models.Model):
test = ForeignKey(Test)
child_title = CharField
class TestChildType(model.Model):
child = ForeignKey(TestChild)
type = BooleanField
测试ChildType模型类型字段使用
filter(type=false).count()
filter(type=true).count()
testFalseCount过滤false值 testTrueCount过滤真值
并想要序列化器
{
item:'mouse',
title:'goood Mouse'
child:[
{
child_title:'childGood'
testFalseCount:4
testTrueCount:3
},
...
]
}
答案 0 :(得分:0)
from rest_framework import serializers
class TestChildSerializer(serializers.ModelSerializer):
testFalseCount = serializers.SerializerMethodField()
testTrueCount = serializers.SerializerMethodField()
@staticmethod
def get_testFalseCount(obj):
return obj.filter(type=false).count()
@staticmethod
def get_testTrueCount(obj):
return obj.filter(type=true).count()
class Meta:
model = Test
class TestSerializer(serializers.ModelSerializer):
child = serializers.SerializerMethodField()
@staticmethod
def get_child(obj):
return [TestChildSerializer(child).data for child in obj.testchild_set.all()]
class Meta:
model = Test