django - get()返回多个主题,过滤器不起作用

时间:2017-05-23 08:45:24

标签: python django python-3.x filter get

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

有什么建议吗?

1 个答案:

答案 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)