具有交叉引用表的反向外键-Django Rest Framework

时间:2018-12-26 06:58:22

标签: django django-rest-framework

我正在尝试创建一个API端点,该端点将提供有关用户及其所属组的摘要数据。

我当前的模型的用户和用户组与成员资格模型关联。

我当前的问题是我似乎无法获得小组成员的名单。

我在这里正确吗?还是有更好的方法来处理具有多对多关系的模型的序列化/查询?

型号:

class UserGroup(models.Model):
    group_id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=30)
    description = models.CharField(max_length=200)
    deleted = models.BooleanField(default=False)


class Membership(models.Model):
    group = models.ForeignKey(UserGroup, on_delete=models.CASCADE, related_name="members")
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user_groups")
    isAdmin = models.BooleanField(default=False)

序列化器:

class MemberSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ('first_name', 'last_name')

class MembershipSerializer(serializers.HyperlinkedModelSerializer):
    name = serializers.ReadOnlyField(source='group.name')
    description = serializers.ReadOnlyField(source='group.description')
    members = MemberSerializer(source='group.members', read_only=True, many=True)

    class Meta:
        model = Membership
        fields = ('name', 'description', 'members')


class UserSerializer(serializers.ModelSerializer):
    groups = MembershipSerializer(source='user_groups', read_only=True, many=True) 

    class Meta:
        model = User
        fields = ('username', 'groups')

当前输出:

{
    "username": "User 1",
    "groups": [
        {
            "name": "Group 1",
            "description": "Test Group",
            "members": [
                {}
            ]
        },
        {
            "name": "Group 2",
            "description": "Test Group 2",
            "members": [
                {}
            ]
        }
    ]
}

预期: “成员”包含UserGroup中的用户列表。

1 个答案:

答案 0 :(得分:0)

我认为您的代码太复杂了。

型号:

from django.contrib.auth import models as dj_models

class Group(models.Model):
    group_id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=30)
    description = models.CharField(max_length=200)
    deleted = models.BooleanField(default=False)
    members = models.ManyToManyField(dj_models.User, through='Membership', related_name='user_groups')


class Membership(models.Model):
    group = models.ForeignKey(Group, on_delete=models.CASCADE)
    user = models.ForeignKey(dj_models.User, on_delete=models.CASCADE)
    isAdmin = models.BooleanField(default=False)

序列化器:

from django.contrib.auth import models as dj_models

class MemberSerializer(serializers.ModelSerializer):

    class Meta:
        model = dj_models.User
        fields = ('username',)


class GroupSerializer(serializers.ModelSerializer):
    members = MemberSerializer(many=True, read_only=True)

    class Meta:
        model = models.Group
        fields = ('name', 'description', 'members')


class UserSerializer(serializers.ModelSerializer):
    groups = GroupSerializer(many=True, read_only=True, source='user_groups')

    class Meta:
        model = dj_models.User
        fields = ('username', 'groups')

输出:

[
{
  "username":"Account 01",
  "groups":[
     {
        "name":"Group 01",
        "description":"Test Group",
        "members":[
           {
              "username":"Account 01"
           }
        ]
     },
     {
        "name":"Group 02",
        "description":"Test Group 2",
        "members":[
           {
              "username":"Account 01"
           }
        ]
     }
  ]
}
]