更正Django多对多字段的串行化实现

quhf5bfb  于 2023-02-10  发布在  Go
关注(0)|答案(1)|浏览(140)

我有两个与多对多领域相关的django模型:

class Member(models.Model):
  user = models.OneToOneField(to=settings.AUTH_USER_MODEL)
  date_of_birth = models.DateField()
  bio = models.TextField()

class Book(models.Model):
  name = models.CharField(max_length=255)
  author= models.CharField(max_length=255)
  description = models.TextField()
  read_by = models.ManyToManyField(to=Member, related_name='books_read')

这些模型的序列化程序是:

class MemberSerializer(serializers.Model):
  id = serializers.IntegerField(read_only=True)
  user_id = serializers.IntegerField(read_only=True)
  class Meta:
    model = Member
    fields = ['id', 'user_id', 'date_of_birth', 'bio']

class BookSerializer(serializers.Model):
  id = serializers.IntegerField(read_only=True)
  class Meta:
    model = Book
    fields = ['id', 'name', 'author', 'bio']

我想创建一个端点,以便能够向成员添加一本书。我可以为它编写序列化程序的唯一方法是:

class BookIdSerializer(serializers.Model):
  class Meta:
    model = Book
    fields = ['id']

  def update(self, **kwargs):
    # logic to add book with passed id to the authenticated user's member profile

然而,这感觉非常错误,原因有两个:
1 -有一个完整的序列化程序对象,它只接收一个图书ID
2 -它甚至不是通用的,因为它执行一个非常具体的功能,即向成员添加一个带有传递的book id的book
我相信有更好的方法来做这件事。如果你知道的话,请指导我。

raogr8fs

raogr8fs1#

您可以使用主键相关字段:

class MemberSerializer(serializers.Model):
  id = serializers.IntegerField(read_only=True)
  user_id = serializers.IntegerField(read_only=True)
  books = serializers.PrimaryKeyRelatedField(many=True, queryset=Book.objects.all())
  class Meta:
    model = Member
    fields = ['id', 'user_id', 'date_of_birth', 'bio', 'books']

这将把相关的书籍放在一个数组中,您可以编辑该数组来添加和删除书籍,从而允许一次添加或删除多本书籍。
有关相关问题/答案,请参见How to use PrimaryKeyRelatedField to update categories on a many-to-many relationship

相关问题