django manytomanyfield字段在drf中deserialize的问题

存在如下模型:

class Person(models.Model):
# …
name = models.CharField(max_length=32)

class Group(models.Model):

# …
members = models.ManyToManyField(Person, through=“Membership”)

class Membership(models.Model):
person = models.ForeignKey(Person)
group = models.ForeignKey(Group)

    class Meta:
    auto_created = True

定义serializer:
class GroupSerializer(serializers.ModelSerializer):
member = serializer.SlugRelatedField(many=True, slug_field=‘name’)
class Meta:
model = Group

此时,由此serializer创建新的Group模型的时候,AttributeError(“Cannot set values on a ManyToManyField which specifies an intermediary model. Use %s.%s’s Manager instead.” % (opts.app_label, opts.object_name)),这个错误是由于DRF在处理M2M关系时,relational fields that target a ManyToManyField with a through model specified are set to read-only。

解决的办法是在Membership的Meta中添加auto_created=True,DRF在反序列化的时候会根据Meta中的auto_created值,在逻辑上以has_though_model属性,利用though_model在完成Group类的实例之后,为实例的members字段添加Membership字段,同时在处理update/delete,能自动根据此属性去实现相应Membership实例的更新和删除操作。

Advertisements
此条目发表在未分类分类目录。将固定链接加入收藏夹。

发表评论

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 更改 )

Twitter picture

You are commenting using your Twitter account. Log Out / 更改 )

Facebook photo

You are commenting using your Facebook account. Log Out / 更改 )

Google+ photo

You are commenting using your Google+ account. Log Out / 更改 )

Connecting to %s