从drf中的多个表序列化数据

时间:2019-03-18 11:38:25

标签: django django-rest-framework

我有两个模型用户和组织。用户模型是默认的Django模型。我的组织模型如下图所示

class Organization(models.Model):
    name = models.CharField(max_length=254, blank=False)
    url = models.URLField(blank=True, null=True)
    year = models.PositiveSmallIntegerField(blank=True, null=True)
    users = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, through='Membership')

    class Meta:
        db_table = '"org_organization"'

class Membership(models.Model):
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        blank=True,
        null=True,
    )
    organization = models.ForeignKey(Organization, on_delete=models.CASCADE)
    position = models.CharField(max_length=254, blank=True, null=True)
    is_admin = models.BooleanField(default=False)

    class Meta:
        db_table = '"org_organization_user"'

用户通过Membership与一个(或多个)组织联系在一起。我可以通过UserReadSerializer来获得有关用户的详细信息,

UserReadSerializer类(serializers.ModelSerializer):

password = serializers.CharField(write_only=True)
organization = MembershipSerializer(source='membership_set', many=True)

class Meta:
    model = UserModel
    fields = ('id', 'email', 'username', 'password', 'first_name', 'last_name', 'organization')

因此,对于用户ID 1,我得到以下响应:

{
    "email": "******@gmail.com",
    "first_name": "Hello",
    "last_name": "User",
    "username": "myuser",
    "organization": [
        {
            "name": "Org1",
            "url": "https://org1.net/",
            "year": 1893,
            "position": "position1",
            "is_admin": true
        },
        {
            "name": "Org2",
            "url": "https://org2.net/",
            "year": 1983,
            "position": "position2",
            "is_admin": false
        }
    ]
}

现在,我想通过PUT方法修改用户组织详细信息,例如,为此,我以与以下类似的格式传递编辑数据:

{
    "email": "******@gmail.com",
    "first_name": "Hello",
    "last_name": "User",
    "username": "myuser",
    "organization": [
        {
            "name": "Org1",
            "position": "changed_position1",
            "is_admin": true
        },
        {
            "name": "Org2",
            "position": "changed_position2",
            "is_admin": true
        }
    ]
}

我为此的序列化器如下:

类UserDetailsS​​erializer(serializers.Serializer):

username = serializers.CharField(required=True)
first_name = serializers.CharField(required=False)
last_name = serializers.CharField(required=False)
email = serializers.EmailField(required=False)

organization = MembershipSerializer(source='membership_set', many=True, required=False)

但是我无法访问organization_name。我得到的只是positionis_admin字段。我在这里缺少什么吗?我正在使用Django 1.11。谢谢您的帮助!

0 个答案:

没有答案