Django Rest Framework多对多序列化未按预期工作

时间:2018-09-19 15:52:26

标签: django django-rest-framework serializer

我进入了stackoverflow,找不到与此错误/错误相关的任何内容。

嗯,我有这个模型:


class ChatRoom(models.Model):
    class Meta:
        app_label = 'chatbot'

    group = models.CharField(max_length=255)
    category = models.CharField(max_length=255)
    name = models.CharField(max_length=255)
    url = models.URLField()
    online = models.IntegerField(default=0)
    recaptcha_hash = models.TextField(null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    bots = models.ManyToManyField(MarkBot, through='ChatBot')

    def __str__(self):
        return '{0}/{1}/{2}'.format(self.group, self.category, self.name)

此序列化器:


class ChatRoomSerializer(ModelSerializer):
    bots = MarkBotSerializer(read_only=True, many=True, allow_null=True)

    class Meta:
        model = ChatRoom
        fields = ['group', 'category', 'name', 'url',
                  'online', 'recaptcha_hash', 'bots']
        read_only_fields = ['pk', 'created_at', 'updated_at']

我的多对多(带有“通过”)中间模型是:


class ChatBot(models.Model):
    class Meta:
        app_label = 'chatbot'

    room_token = models.TextField()
    bot = models.ForeignKey(MarkBot, on_delete=models.CASCADE)
    chat_room = models.ForeignKey(ChatRoom, on_delete=models.CASCADE)

最后,我的APIview,将数据检索到客户端:

class ChatRoomsActive(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request, *args, **kwargs):
        user = request.user

        try:
            campaign = Campaign.objects.get(user=user, is_active=True)
            chat_rooms = ChatRoom.objects.filter(campaign=campaign)
            rooms = ChatRoomSerializer(
                data=list(chat_rooms.values()),
                many=True
            )

            if rooms.is_valid():
                return Response({
                    'data': rooms.data,
                    'error': None
                })

        except Campaign.DoesNotExist:
            return Response({
                'data': [],
                'error': 'Campanha inválida'
            }, status=status.HTTP_400_BAD_REQUEST)

        except Exception:
            return Response({
                'data': [],
                'error': 'Ocorreu um erro inesperado em sua requisição'
            }, status=status.HTTP_400_BAD_REQUEST)

        return Response({
            'data': [],
            'error': 'Não foi possível obter as salas ativas'
        }, status=status.HTTP_400_BAD_REQUEST)

而且,在我所有的JSON序列化结果中,即使我将机器人连接到房间,我也会收到属性“ bots”等于“ null”。

预期产量

与该特定房间相连的漫游器列表;如果没有,则为null。

谢谢你!

1 个答案:

答案 0 :(得分:2)

chat_rooms.values()可能没有相关的bots,并且调用is_valid进行序列化是没有道理的-我不确定它是否可以工作。

rooms = ChatRoomSerializer(
    instance=list(chat_rooms),
    many=True
)

return Response({
    'data': rooms.data,
    'error': None
})