如何在Django Rest框架中合并REST API的两个对象?

时间:2019-04-23 15:24:14

标签: json django python-3.x django-rest-framework django-views

这是我的views.py文件

class NewsChannelListView(ObjectMultipleModelAPIView):

    def get_querylist(self, *args, **kwargs):
        userId = self.request.user.id
        queryset = [
            {'queryset': News_Channel.objects.all(),
             'serializer_class': NewsChannelSerializers},
            {'queryset': Count.objects.filter(userId=userId),
             'serializer_class': CountSerializers},
        ]
        return queryset

我从这个观点中得到了关注

{
    "News_Channel": [
        {
            "id": 2,
            "name": "Republic",
            "info": "Arnab Goswami News channel",
            "image": "https://fourthpillar-static.s3.amazonaws.com/media/repiblic_1bRFWNZ.png",
            "website": "https://www.repu",
            "total_star": 10,
            "total_user": 2
        },
        {
            "id": 1,
            "name": "NDTV",
            "info": "India News Media",
            "image": "https://fourthpillar-static.s3.amazonaws.com/media/ndtv_WH67OhA.png",
            "website": "https://ndtv.com",
            "total_star": 18,
            "total_user": 2
        }
    ],
    "Count": [
        {
            "userId": 1,
            "channelId": 2,
            "rate": 6
        },
        {
            "userId": 1,
            "channelId": 1,
            "rate": 8
        }
    ]
}

有什么办法可以获取单个对象.count中的通道ID 2与新闻频道中的ID 2合并,count中的通道ID 1与新闻频道中的ID 1合并。所以最终回应应该是这样

{
    "News_Channel": [
        {
            "id": 2,
            "name": "Republic",
            "info": "Arnab Goswami News channel",
            "image": "https://fourthpillar-static.s3.amazonaws.com/media/repiblic_1bRFWNZ.png",
            "website": "https://www.repu",
            "total_star": 10,
            "total_user": 2,
            "userId": 1,
            "rate": 6
        },
        {
            "id": 1,
            "name": "NDTV",
            "info": "India News Media",
            "image": "https://fourthpillar-static.s3.amazonaws.com/media/ndtv_WH67OhA.png",
            "website": "https://ndtv.com",
            "total_star": 18,
            "total_user": 2,
            "userId": 1,
            "rate": 8
        }
    ],
}

模型代码

class News_Channel(models.Model):
    name = models.TextField(blank=False)
    info = models.TextField(blank=False)
    image = models.FileField()
    website = models.TextField()
    total_star = models.PositiveIntegerField(default=0)
    total_user = models.IntegerField()

    class Meta:
        ordering = ["-id"]

    def __str__(self):
        return self.name


class Count(models.Model):
    userId = models.ForeignKey(User, on_delete=models.CASCADE)
    channelId = models.ForeignKey(News_Channel, on_delete=models.CASCADE)
    rate = models.PositiveIntegerField(default=0)

    class Meta:
        ordering = ["-id"]

我正在使用django 2.1.7和djangorestframework == 3.9.2。

0 个答案:

没有答案