AssertionError:期望从视图返回“ Response”,“ HttpResponse”或“ HttpStreamingResponse”,但是收到了“ <class'nonetype'=“”>`

时间:2018-11-18 15:46:00

标签: python django django-models django-orm

我有以下将用户作为成员的房间对象。

class Room(Base):
    name = models.CharField(db_index=True, unique=True, max_length=255)
    members = models.ManyToManyField(User, blank=True)

我正试图找到只有两个特定成员的会议室,

if Room.objects.filter(members__id=first.id).filter(members__id=second.id).exists():
                    rooms = Room.objects.filter(members__id=first.id).filter(members__id=second.id)
                    for room in rooms:
                        print(room.members.count)
                        if room.members.count == 2:
                            return Response({"Success": RoomSerializer(room).data}, status=status.HTTP_200_OK)

我知道存在一个Room对象,该对象只有两个成员。但是我最终遇到了这个错误,

AssertionError: Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>`

任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:1)

正如异常所说,在视图末尾,总是返回一个响应。在您当前的代码中,如果逻辑不匹配,则返回None。因此,像这样更新代码:

if Room.objects.filter(members__id=first.id).filter(members__id=second.id).exists():
                rooms = Room.objects.filter(members__id=first.id).filter(members__id=second.id)
                for room in rooms:
                    print(room.members.count)
                    if room.members.count == 2:
                        return Response({"Success": RoomSerializer(room).data}, status=status.HTTP_200_OK)
return Response({"Failed": True}, status=status.HTTP_400_BAD_REQUEST) # <-- Return a bad request maybe at the end if all logic fails

答案 1 :(得分:1)

QuerySet count()是一种方法(type(room.members.count)返回<class 'method'>),应这样调用。只是改变

room.members.count

room.members.count()

它应该可以正常工作。