Django REST框架:ListCreateAPI和RetrieveUpdateDelete Api用于复杂的外键关系

时间:2018-03-14 20:16:15

标签: python django rest api django-rest-framework

道歉,如果这看起来微不足道,但我想知道Django最常用的方法是什么。以下是列出的模型,视图和序列化器供参考。

有3种型号。我只是为每个字段显示相关字段,尽管它们有多个字段。现在,一个博客可以有多个作者参与其中。同样,一位作者或撰稿人可以为多个博客做出贡献。

class Blog(models.Model):
    title = models.CharField(max_length="120")
    ...

class Author(models.Model):
    title = models.CharField(max_length="120")
    ...

class BlogAuthor(models.Model):
    blog = models.ForeignKey('Blog') 
    author = models.ForeignKey('Author')
    creator = models.ForeignKey('auth.User')
    # Should the above relations be a Foreign Key or ManyToMany Field

我正在使用DRF 3.0创建以下API:

        GET /blogs/1/author : to get a list of authors for the blog identified by id 1
Sample Output: {
                 id: 1,
                 blog_id:1,
                 authors:[1,2,3] #or authors:{1,2,3}
               }
        POST /blogs/1/author: create which authors are related to the blog 1
        GET /blogs/1/author/1: show details of the author 1 in context of the blog 1; for ex, author 1 may have contributed 300 words to blog 1 so this would return that along with some other details, say name of the author, picture of the author etc
        DELETE /blogs/1/author/1 : deletes the relation between blog 1 and author 1, thought both entities exist; just the relationship between them is deleted

相关网址:

path('blogs/<int:blog_pk>/authors/', views.BlogAuthorList.as_view(), name='blogauthor-list'),
path('blogs/<int:blog_pk>/authors/<int:pk>', views.BlogAuthorList.as_view(), name='blogauthor-detail'),

我也创建了视图和序列化器,但我不太确定。

Serializer:
class BlogAuthor(serializers.ModelSerializer):
        creator = serializers.ReadOnlyField(source='creator.username')

        class Meta:
            model = BlogAuthor
            fields = ('id', 'blog', 'author', 'creator')

    View:
    class BlogAuthorList(generics.ListCreateAPIView):
        queryset = BlogAuthor.objects.all() # notsure
        serializer_class = BlogAuthorSerializer
        permission_classes = (permissions.IsAuthenticatedOrReadOnly,)

        #The below was working early but since i introduced the new URLs, see paths above am getting error as shown above
        def create(self, request, *args, **kwargs):
            public_personas = request.data.get('authors')
    #To handle multiple authors sent from API, ie, to handle requests such as #: 
   # {
   #     "blog": 1,
   #     "author": [1,3]
   # }
            data = {}
            response_data = []
            response_dict = {}
            for author in authors:
                data['blog'] = request.data.get('blog')
                data['author'] = author
                serializer = self.get_serializer(data=data)
                if serializer.is_valid():
                    self.perform_create(serializer)
                    headers = self.get_success_headers(serializer.data)
                    response_data.append(serializer.data)
                else:
                    return Response(data=serializer.errors, status=status.HTTP_400_BAD_REQUEST)
            response_dict['data'] = response_data
            return Response(response_dict, status=status.HTTP_201_CREATED, headers=headers)

        def perform_create(self, serializer):
            serializer.save(creator=self.request.user)

        # def list(self, request):
        #   Not Sure How To Do This


    #Not sure about this.
    class BlogAuthor(generics.RetrieveDestroyAPIView):
        ???

这是一个很长的问题。对于那个很抱歉。请让我知道你的想法,并指出我如何做到这一点的正确方向。我觉得这是一个非常普遍的事情,所以应该直截了当,但现在已经抓了我一段时间。

由于

0 个答案:

没有答案