I use one Serializer in many different places in my project. I need to use one annotation but the problem is that I don't want to annotate it in all views so I would like to do universal annotation in the Serializer itself.
It is possible?
Now I need to do this before every serialization:
City.objects....filter....annotate(
number_of_users_here_now=Count('current_userprofiles'))
I tried:
class NumberOfUsersInCityNowField(serializers.Field):
def to_native(self, value):
count = value.annotate(
number_of_users_here_now=Count('current_userprofiles'))['current_userprofiles__count']
return count
class CityMapSerializer(serializers.ModelSerializer):
number_of_users_here_now = NumberOfUsersInCityNowField()
class Meta:
model = City
fields = ('place_id', 'lat', 'lng', 'number_of_users_here_now', 'formatted_address')
This Serializer returns:
AttributeError at /api/ajax-check-trip-creation Got AttributeError when attempting to get a value for field
number_of_users_here_nowon serializerCityMapSerializer. The serializer field might be named incorrectly and not match any attribute or key on theCityinstance. Original exception text was: 'City' object has no attribute 'number_of_users_here_now'.
EDIT
class NumberOfUsersInCityNowField(serializers.PrimaryKeyRelatedField):
def get_queryset(self):
return City.objects.annotate(
number_of_users_here_now=Count('current_userprofiles'))
class CityMapSerializer(serializers.ModelSerializer):
# number_of_users_here_now = serializers.IntegerField()
number_of_users_here_now = NumberOfUsersInCityNowField()
class Meta:
model = City
fields = ('place_id', 'lat', 'lng', 'number_of_users_here_now', 'formatted_address')
But
serializers.CityMapSerializer(City.objects.all()[:3],many=True).data
still returns:
AttributeError: 'City' object has no attribute 'number_of_users_here_now'