Wahtdbogh Wahtdbogh - 1 year ago 98
Python Question

django - get() returned more than one topic and filter doesn't work

I have a problem with get() in Django. To wit I have such function:

try:
sth = Object.objects.get(t=request.GET.get('data'))
if request.method == 'GET':
serializer = ObjectSerializer(sth)
return Response(serializer.data)


I got error:

get() returned more than one Object -- it returned 2!


So I have swapped get for filter:

sth = Object.objects.filter(t=request.GET.get('data'))


But now I get error:

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


Any suggestions?

Answer Source

Simple specify many=True when creating a serializer from queryset.

  sth = Object.objects.filter(t=request.GET.get('data'))
  if request.method == 'GET':
      serializer = ObjectSerializer(sth, many=True) 
      return Response(serializer.data)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download