我在Django中遇到了get()问题。即使我有这样的功能:
try:
sth = Object.objects.get(t=request.GET.get('data'))
if request.method == 'GET':
serializer = ObjectSerializer(sth)
return Response(serializer.data)
我收到了错误:
get() returned more than one Object -- it returned 2!
所以我换了get for filter:
sth = Object.objects.filter(t=request.GET.get('data'))
但现在我收到了错误:
AttributeError: Got AttributeError when attempting to get a value for field `data` on serializer `ObjectSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `QuerySet` instance.
Original exception text was: 'QuerySet' object has no attribute 'data'.
有什么建议吗?
答案 0 :(得分:1)
从queryset创建序列化程序时,简单指定many = True。
sth = Object.objects.filter(t=request.GET.get('data'))
if request.method == 'GET':
serializer = ObjectSerializer(sth, many=True)
return Response(serializer.data)