将计数字段添加到Django Rest Framework序列化器 [英] Add a count field to a django rest framework serializer
问题描述
我正在对内置的django组模型进行序列化,并希望向序列化器添加一个字段,以对组中的用户数量进行计数。我当前正在使用以下序列化器:
I am serializing the built-in django Group model and would like to add a field to the serializer that counts the number of users in the group. I am currently using the following serializer:
class GroupSerializer(serializers.ModelSerializer):
class Meta:
model = Group
fields = ('id', 'name', 'user_set')
这将返回组ID和名称以及该组中的一组用户(用户ID):
This returns the group ID and name and an array of users (user IDs) in the group:
{
"id": 3,
"name": "Test1",
"user_set": [
9
]
}
我想要的是输出内容:
{
"id": 3,
"name": "Test1",
"user_count": 1
}
任何帮助将不胜感激。谢谢。
Any help would be appreciated. Thanks.
推荐答案
这应该有效
class GroupSerializer(serializers.ModelSerializer):
user_count = serializers.SerializerMethodField()
class Meta:
model = Group
fields = ('id', 'name','user_count')
def get_user_count(self, obj):
return obj.user_set.count()
这会将 user_count
字段添加到序列化器,其值由<$ c设置$ c> get_user_count ,它将返回 user_set
的长度。
This adds a user_count
field to your serializer whose value is set by get_user_count
, which will return the length of the user_set
.
您可以在以下位置找到有关SerializerMethodField的更多信息: http://www.django-rest-framework.org / api-guide / fields /#serializermethodfield
You can find more information on SerializerMethodField here: http://www.django-rest-framework.org/api-guide/fields/#serializermethodfield
这篇关于将计数字段添加到Django Rest Framework序列化器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!