52👍
✅
This should work
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()
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
.
You can find more information on SerializerMethodField here: http://www.django-rest-framework.org/api-guide/fields/#serializermethodfield
79👍
A bit late but short answer. Try this
user_count = serializers.IntegerField(
source='user_set.count',
read_only=True
)
👤Lal
- [Django]-Which Stack-Overflow style Markdown (WMD) JavaScript editor should we use?
- [Django]-How to add an HTTP header to all Django responses
- [Django]-How to set the timezone in Django
4👍
Everyone’s answer looks great. And I would like to contribute another options here – to use @property
if-and-only-if you can modify the target model.
Assume you can modify the Group
model.
class Group(models.Model):
@property
def user_count(self):
return self.user_set.count
Then you can simply add 'user_count'
to fields
in your serializer.
I’m using this approach but I’m thinking to switch to the serializer approach as other’s answer here. Thanks everyone.
- [Django]-Is it possible to generate django models from the database?
- [Django]-Unable to find a locale path to store translations for file __init__.py
- [Django]-Django return HttpResponseRedirect to an url with a parameter
Source:stackexchange.com