我在项目的许多不同地方使用一个Serializer
。我需要使用一个注释,但问题是我不想在所有 View 中对其进行注释,因此我想在 Serializer
本身中进行通用注释。
可能吗?
现在我需要在每次序列化之前执行此操作:
City.objects....filter....annotate(
number_of_users_here_now=Count('current_userprofiles'))
我尝试过:
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')
此序列化器
返回:
AttributeError at /api/ajax-check-trip-creation Got AttributeError when attempting to get a value for field
number_of_users_here_now
on serializerCityMapSerializer
. The serializer field might be named incorrectly and not match any attribute or key on theCity
instance. Original exception text was: 'City' object has no attribute 'number_of_users_here_now'.
编辑
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')
但是
serializers.CityMapSerializer(City.objects.all()[:3],many=True).data
仍然返回:
AttributeError: 'City' object has no attribute 'number_of_users_here_now'
最佳答案
您可以仅使用查询集的 count
方法 SerializerMethodField
:
class CityMapSerializer(serializers.ModelSerializer):
number_of_users_here_now = SerializerMethodField()
def get_number_of_users_here_now (self, obj):
return obj.current_userprofiles.count()
UPD
此外,为了避免 n+1 查询,您可以尝试实现 NumberOfUsersInCityNowField
序列化器的 get_queryset
方法:
class NumberOfUsersInCityNowField(serializers.PrimaryKeyRelatedField):
def get_queryset(self):
return City.objects.annotate(
number_of_users_here_now=Count('current_userprofiles'))['current_userprofiles__count']
关于python - Django Rest Framework - 自动注释查询集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48153585/