关于python:aggregate(Max(’id’))返回异常’str’对象没有属性’email’

aggregate(Max('id')) returns exception 'str' object has no attribute 'email'

我一直试图让用户拥有最高的ID,但没有成功。这是我的用户模型:

1
2
3
class User(models.Model):
    email=models.EmailField(unique=True, null=False)
    name=models.TextField(null=True)

其序列化程序:

1
2
3
4
class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'email', 'name')

视图:

1
2
3
4
5
class GetHighestValue(generics.ListAPIView):
    serializer_class = UserSerializer

    def get_queryset(self):
        return User.objects.aggregate(Max('id'))

Got AttributeError when attempting to get a value for field email on
serializer UserSerializer. The serializer field might be named
incorrectly and not match any attribute or key on the str instance.
Original exception text was: 'str' object has no attribute 'email'.

回溯:

Traceback (most recent call last):
File
"/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py",
line 149, in get_response
response = self.process_exception_by_middleware(e, request) File"/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py",
line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File"/usr/local/lib/python2.7/dist-packages/django/views/decorators/csrf.py",
line 58, in wrapped_view
return view_func(*args, **kwargs)
File"/usr/local/lib/python2.7/dist-packages/django/views/generic/base.py",
line 68, in view
return self.dispatch(request, *args, **kwargs)
File"/home/user/.local/lib/python2.7/site-packages/rest_framework/views.py",
line 466, in dispatch
response = self.handle_exception(exc)
File"/home/user/.local/lib/python2.7/site-packages/rest_framework/views.py",
line 463, in dispatch
response = handler(request, *args, **kwargs)
File"/home/user/.local/lib/python2.7/site-packages/rest_framework/generics.py",
line 201, in get
return self.list(request, *args, **kwargs)
File"/home/user/.local/lib/python2.7/site-packages/rest_framework/mixins.py",
line 48, in list
return Response(serializer.data)
File"/home/user/.local/lib/python2.7/site-packages/rest_framework/serializers.py",
line 674, in data
ret = super(ListSerializer, self).data
File"/home/user/.local/lib/python2.7/site-packages/rest_framework/serializers.py",
line 239, in data
self._data = self.to_representation(self.instance)
File"/home/user/.local/lib/python2.7/site-packages/rest_framework/serializers.py",
line 614, in to_representation
self.child.to_representation(item) for item in iterable
File"/home/user/.local/lib/python2.7/site-packages/rest_framework/serializers.py",
line 463, in to_representation
attribute = field.get_attribute(instance)
File"/home/user/.local/lib/python2.7/site-packages/rest_framework/fields.py",
line 422, in get_attribute
raise type(exc)(msg) AttributeError: Got AttributeError when attempting to get a value for field email on serializer
UserSerializer. The serializer field might be named incorrectly and
not match any attribute or key on the str instance. Original
exception text was: 'str' object has no attribute 'email'.


问题就在这里

1
2
def get_queryset(self):
    return User.objects.aggregate(Max('id'))

预期的返回值是一个查询集。但聚合不返回查询集。使用user.objects.get()也不会返回查询集。返回查询集的唯一方法是使用all()filter()

1
2
def get_queryset(self):
    return User.objects.order_by(-'id')[0:1]

这里隐含了all(),并且[0:1]确保返回的是iterable而不是单个对象。


我在扩大赵希的写作范围。尝试将视图的get_queryset()方法更改为下面的方法。不是返回聚合的结果(不是查询集,因为已经对其进行了评估),而是使用该数字查找与max id关联的实例并返回该实例(即查询集)。

1
2
3
4
5
6
class GetHighestValue(generics.ListAPIView):
    serializer_class = UserSerializer

    def get_queryset(self):
        max_id = User.objects.aggregate(Max('id')).get('id__max')
        return User.objects.filter(id=max_id)

免责声明:我在手机上写了这篇文章,我无法测试它。请在评论中告诉我这是否解决了您的问题,我将根据需要进行编辑。


问题在你看来,

当您试图获取查询集时,您使用的是aggregate()方法。

但是aggregate()不返回queryset,而是一个名称-值对的字典。有关详细信息,请参阅https://docs.djangoproject.com/en/1.9/topics/db/aggregation

aggregate()不同,annotate()不是一个终止子句。annotate()子句的输出是一个查询集;这个查询集可以使用任何其他的查询集操作进行修改,包括filter()order_by()

希望有帮助。