首页 > 解决方案 > API Django Rest Framework 上的多对多字段 POST 请求

问题描述

所以我有3个感兴趣的模型:

models.py
class Author(models.Model): #Author of books
name = models.CharField(max_length = 100)

    @property    # This is code to get the books linked to an author 
    def books(self):
        book = Book.objects.filter(authors = self.id)
        return ', '.join(map(str,book)) #This makes the book list in this format "A, B, C"

    def __str__(self):
        return self.name.title()


class Genre(models.Model): #Genre of books
name = models.CharField(max_length = 50, unique = True)

    @property
    def books(self):
        book = Book.objects.filter(genre = self.id)
        return ', '.join(map(str,book))

    def __str__(self):
        return self.name.title()

class Book(models.Model):
    name = models.CharField(max_length = 150,)   #Name of books
    authors = models.ManyToManyField(Author,)     #Many to many because multiple books can have multiple authors
     genre = models.ManyToManyField(Genre)

    def __str__(self):
        return self.name.title()

这些是模型,流派和作者都与书籍有多对多的关系

serializers.py
class AuthorListSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Author
        fields = ('name',)

class GenreListSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Genre
        fields = ('name',)

class BookListSerializer(serializers.ModelSerializer):
    authors = AuthorListSerializer(many = True,) #To represent the relationship as a string instead of id
    genre = serializers.SlugRelatedField(many = True, queryset = models.Genre.objects.all(),slug_field = 'name')

    class Meta:
        model = models.Book
        fields = ('name','authors','rating', 'genre')

class BookDetailSerializer(serializers.ModelSerializer):
    publisher = serializers.SlugRelatedField(queryset = models.Publisher.objects.all(), slug_field= 'name') #To display publisher name instead of id

    authors = serializers.StringRelatedField(many = True,) #To represent the relationship as a string instead of id
    genre = serializers.StringRelatedField(many = True,)

    class Meta:
        model = models.Book
        fields = ('name', 'authors', 'rating','genre',
                  'publisher', 'total_qty', 'avail_qty',
                  'pub_date','isbn','price',)

所以在我的 Django-Rest-Framework Browsable api 中,Normal ForeignKey 字段显示了它们的选项以创建一个新的对象实例。例如,“BookDetailSerializer”中的发布者将所有发布者显示为 POST 或 PUT 或 PATCH 请求的选项。但是对于包括流派和作者在内的多对多字段,它不仅是空白的,而且我似乎无法输入任何内容。我曾尝试使用 DRF-writable-nested 第三方包,但没有任何改变:

    class BookListSerializer(WritableNestedModelSerializer):
        authors = AuthorListSerializer(many = True,) #To represent the relationship as a string instead of id
        genre = serializers.SlugRelatedField(many = True,
                                             queryset = models.Genre.objects.all(),slug_field = 'name')

我的问题是如何通过 DRF 可浏览 api 使用我的作者和流派列表发出 POST 请求?提前致谢!!

此图显示了可用于发出涉及发布者的 POST 请求的选项

此图像显示您不能为涉及 Genre 和 Authors 的多对多关系的 POST 请求添加任何输入。

更新:所以我加了一个create方法,还是不行,如下图:

class BookListSerializer(serializers.ModelSerializer):
authors = AuthorListSerializer(many = True,) #To represent the relationship as a string instead of id
genre = serializers.SlugRelatedField(many = True,
                                             queryset = models.Genre.objects.all(),slug_field = 'name')


class Meta:
    model = models.Book
    fields = ('name','authors','rating', 'genre')


def create(self,validated_data):
    authors_data = models.Author.objects.all()
    book = Book.objects.create(authors = authors_data,**validated_data,)
    return book

我能做些什么?

标签: djangodjango-modelsdjango-rest-frameworkdjango-serializer

解决方案


在挣扎了 4 天后,我找到了答案当处理多对多关系并且您希望代码如下所示。

 class BookListSerializer(serializers.ModelSerializer):

class Meta:
    model = models.Book
    fields = ('name','authors','rating', 'genre')
    depth = 1

添加深度允许嵌套关系完全序列化。因为关系是嵌套的,并且是多对多关系,所以您必须在 views.py 中创建自己的创建函数,如下所示:

 class BookViewSet(GetSerializerClassMixin, viewsets.ModelViewSet):

queryset = models.Book.objects.all()
serializer_class = serializers.BookDetailSerializer
serializer_action_classes = {'list': serializers.BookListSerializer}
permission_classes = [IsAdminOrReadOnly, permissions.IsAuthenticated,] 

def create(self,request, *args, **kwargs):
    data = request.data

    new_book = models.Book.objects.create(name = data["name"], publisher = models.Publisher.objects.get(id = data["publisher"]),
                                        pub_date = data["pub_date"],
                                        price = data["price"],
                                        isbn = data['isbn'],)
    new_book.save()
    
    for author in data['authors']:
        author_obj = models.Author.objects.get(name = author['name'])
        new_book.authors.add(author_obj)

    for gen in data['genre']:
        gen_obj = models.Genre.objects.get(name = gen['name'])
        new_book.genre.add(gen_obj)

    serializer = serializers.BookListSerializer(new_book)
    
    return Response(serializer.data)

对于多对多关系,您必须在保存对象后创建它们并手动将它们添加到对象中。那里存在一个外键关系“发布者”对于该关系,您必须手动指向它在数据库中的位置,因此下面的代码。

 name = data["name"], publisher = models.Publisher.objects.get(id = data["publisher"]),

对于问题中的 Detail 书籍序列化程序,它与 BookListSerializer 相同

这就是我能够在多对多关系中处理 POST 请求的方式


推荐阅读