2016-05-26 5 views
2

私は最高のIDを持つユーザーを獲得しようとしていますが、成功しません。 :aggregate(Max( 'id'))は例外 'str'を返します。オブジェクトには 'email'という属性はありません

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

それは、シリアライザです:

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

ビュー:

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'.

+0

ここに完全なトレースを入れてください – e4c5

+0

'python manage.py makemigrations'と' python manage.py migrate'を実行しましたか?また、 'latest()'を使うことで、あなたの要求をより簡単に満たすことができます。 https://docs.djangoproject.com/en/1.9/ref/models/querysets/#django.db.models.query.QuerySet.latest –

+0

うん、私は両方を走らせた。私も最新の( 'id')を使ってみましたが、次のエラーが表示されます: '' User ''オブジェクトは反復可能ではありません ' –

答えて

1

問題が予想される戻り値がクエリセットである、ここで

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

です。しかし、集合体はクエリーセットを返さない。 User.objects.get()を使用してもクエリーセットは返されません。クエリセットを返すための唯一の方法は、すべてのall()またはfilter()

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

を使用することです()ここで暗示し、[0:1]されますが、反復可能ではなく、単一のオブジェクトを返すされることが保証されます。

+0

私はあなたがしたようにorder_byを使って問題を昨日解決しましたが、なぜ集約が機能していないのか分かりませんでした。説明ありがとう :) –

1

問題はあなたのビューである、

あなたはクエリセットを取得しようとしている、あなたはaggregate()メソッドを使用しています。

BUT aggregate()は返さないクエリーセットですが、名前と値のペアの辞書です。 詳細はhttps://docs.djangoproject.com/en/1.9/topics/db/aggregationを参照

aggregate()とは異なり、annotate()は終端節ではありません。 annotate()句の出力はQuerySetです。このQuerySetは、filter(),order_by()を含む他のQuerySet操作を使用して変更できます。

希望があります。

+0

クエリーセットのコードを追加できますか? –

1

私はzhaochyが書いたものを拡大しています。ビューのget_queryset()メソッドを以下に変更してみてください。集計の結果を返す代わりに(すでに評価済みであるため、クエリーセットではありません)、その数値を使用して最大IDに関連付けられたインスタンスを検索し、それを返します(クエリーセットです)。

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) 

免責事項:私はそれをテストすることができなかったところ、私は自分の携帯電話でこの記事を書きました。私がコメントでこれがあなたの問題を解決するかどうかを教えてください。私は必要に応じて編集します。

+0

次のエラーが表示されます: ''ユーザ 'オブジェクトは反復可能ではありません ' 何か不足していますか? –

+0

ええ、ええ、おそらくあなたのプロジェクトは不安定な状態です。これは新鮮なDjangoプロジェクトでうまくいくはずです。クエリーセットは本質的に反復可能です。 https://docs.djangoproject.com/en/1.9/ref/models/querysets/ –

+0

期待される戻り値がクエリーセットの場合は、単一のUserオブジェクトを返します – e4c5

関連する問題