V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
lsl
V2EX  ›  问与答

Django DRF model 多对多手动指定,表序列化问题.

  •  
  •   lsl · 2018-03-28 23:02:43 +08:00 · 4003 次点击
    这是一个创建于 2467 天前的主题,其中的信息可能已经有所发展或是发生改变。

    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
    
    
    3 条回复    2018-09-03 00:44:50 +08:00
    dalang
        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
    lsl
        2
    lsl  
    OP
       2018-03-29 09:11:04 +08:00
    感谢回复,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.
    hiths
        3
    hiths  
       2018-09-03 00:44:50 +08:00
    Membership 里面加一个 class Meta: auto_created = True
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1222 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 23ms · UTC 18:03 · PVG 02:03 · LAX 10:03 · JFK 13:03
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.