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

标签 python django serialization django-rest-framework django-orm

我在项目的许多不同地方使用一个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/

相关文章:

c# - 继续挑战 : Serializing Math for Projecting to C# and Javascript

java - 如何找到Java类中哪些对象不能被序列化?

python - 一热编码字符

python - Django:在数据迁移中创建 super 用户

python - 如何使用外键将帖子添加到 django 用户模型

serialization - 如何保存/序列化 QVariant 即 QVector<int>

python - 使用 Tornado 和 SUDS 的异步 SOAP 调用

python - cv2.approxPolyDP() , cv2.arcLength() 这些是如何工作的

python - 如何从另一个Python例程调用一个Python例程?

python - 如何通过模板在 django 模型选择中添加选项