Django REST API多个记录相同类别

时间:2017-10-29 21:48:41

标签: python django rest

Django Rest API存在问题,我的创建者表中有2条记录。 第一个记录有类别"游戏"第二个记录有类别"教育"现在一切都还可以,但是当我添加Thirds记录与Category" Education"(同一类别的第一条记录)时,当我拨打该类别(游戏)的所有记录时,我收到了错误。

我想要同一类别的多个记录

model.py

class Creators(models.Model):
    title=models.CharField(max_length=200)
    link = models.CharField(max_length=200)
    subscriber = models.PositiveIntegerField()
    country = models.CharField(max_length=100)
    email = models.CharField(max_length=100)
    description = models.TextField(max_length=2000)
    category = models.CharField(max_length=100)
    socialLinks = models.TextField(max_length=2000)

    class Meta:
        ordering = ('title',)

serializer.py

class CreatorsSerializer(serializers.ModelSerializer):

    class Meta:
        model = Creators
        fields = "__all__"

views.py

class CreatorsList(APIView):

    def get(self,request,category):
        creator = Creators.objects.get(category=category)
        serializer = CreatorsSerializer(creator)
        return Response(serializer.data)
    def post(self):
        pass

urls.py

url(r'^creators/(?P<category>\w+)/$', views.CreatorsList.as_view()),

当我运行 example.com/creators/Gaming / 时,它会给我完美的输出(现在我只有2条记录)

{
    "id": 1,
    "title": "channel1",
    "link": "https://www.youtube.com/channel/UCJbPGzawDH1njbqV-D5HqKw",
    "subscriber": 2000,
    "country": "PK",
    "email": "ishaq@gmail.com",
    "description": "ddkndkndkdknkdnkndddkndkndkdknkdnkndddkndkndkdknkdnkndddkndkndkdknkdnkndddkndkndkdknkdnkndddkndkndkdknkdnkndddkndkndkdknkdnkndddkndkndkdknkdnkndddkndkndkdknkdnkndddkndkndkdknkdnkndddkndkndkdknkdnkndddkndkndkdknkdnknd",
    "category": "Gaming",
    "socialLinks": "ddkndkndkdknkdnkndddkndkndkdknkdnkndddkndkndkdknkdnknd"
}

但是当我添加相同类别(游戏)的第三条记录时,错误显示

MultipleObjectsReturned at /creators/Education/
get() returned more than one Creators -- it returned 2!

我还在views.py中添加了多个= True,但即使1个记录的类别在这种情况下也不起作用,没有任何反应

class CreatorsList(APIView):

    def get(self,request,category):
        creator = Creators.objects.get(category=category,many=True)
        serializer = CreatorsSerializer(creator)
        return Response(serializer.data)
    def post(self):
        pass

1 个答案:

答案 0 :(得分:1)

您需要使用过滤器而不是获取此行

creator = Creators.objects.get(category=category)

方法get()期望只返回一条记录,如果返回更多则给出此错误。那么正确的是:

creator = Creators.objects.filter(category=category)