django DRF 字段多对多,"through='Membership'"手动指定表.通过 serializers.ModelSerializer 序列化 Group 表后,不能在 Group 下对"members "多对多的数据进行添加,"members"该字段属性显示"read_only": true.我找了一天没找到解决办法,请求帮助! 另外发现如果 ManyToMany 的表是自动生成的就没有这个问题.
#model.py
from django.db import models
class Person(models.Model):
name = models.CharField(max_length=128)
def __str__(self):
return self.name
class Group(models.Model):
name = models.CharField(max_length=128)
members = models.ManyToManyField(Person, through='Membership')
def __str__(self):
return self.name
class Membership(models.Model):
person = models.ForeignKey(Person, on_delete=models.CASCADE)
group = models.ForeignKey(Group, on_delete=models.CASCADE)
date_joined = models.DateField()
invite_reason = models.CharField(max_length=64)
#serializers.py
from rest_framework import serializers
from .models import Group
class GroupSerializer(serializers.ModelSerializer):
class Meta:
model = Group
fields = ('name','members')
#views.py
from django.shortcuts import render
from rest_framework import viewsets
from .models import Group,Membership
from .serializers import GroupSerializer
# Create your views here.
class GroupViewSet(viewsets.ModelViewSet):
queryset = Group.objects.all()
serializer_class = GroupSerializer
1
dalang 2018-03-29 00:07:47 +08:00
```
By default, relational fields that target a ManyToManyField with a through model specified are set to read-only. ``` 我觉得比较好的做法是自己为 members 写一个 custom field 类型,然后在这个类型里处理,write 的话,应该需要自己写 to_internal_value |
2
lsl OP 感谢回复,Django Restful Framework 目前学的还不够深,我就是奇怪为什么 ManyToManyField 自动生成的表,同样是用 ModelSerializer 序列化,"members"该字段属性就是"read_only": false;而手动指定中间表序列化"read_only": true. 官方文档中说的"By default, relational fields that target a ManyToManyField with a through model specified are set to read-only. "是不是意味手动指定中间表那么该字段属性就是"read_only": true.
|
3
hiths 2018-09-03 00:44:50 +08:00
Membership 里面加一个 class Meta: auto_created = True
|