gpt4 book ai didi

python - Django Rest Framework - 自动注释查询集

转载 作者:太空宇宙 更新时间:2023-11-03 14:17:32 24 4
gpt4 key购买 nike

我在项目的许多不同地方使用一个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 serializer CityMapSerializer. The serializer field might be named incorrectly and not match any attribute or key on the City 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com