Django ORM-从中间表添加数据

时间:2018-11-07 11:27:22

标签: django database join orm django-queryset

我的django rest应用程序具有以下多对多数据结构:

class User(Model):

    name = models.CharField(max_length=64)
    memberships = models.ManyToManyField('Membership', through='UserMembership', related_name='users')

    def __str__(self):
        return "{}".format(self.name)

class Membership(Model):

    name = models.CharField(max_length=64)

    def __str__(self):
        return "{}".format(self.name)

class UserMembership(Model):

    user = models.ForeignKey('User', on_delete=models.CASCADE)
    membership = models.ForeignKey('Membership', on_delete=models.CASCADE)
    reason = models.CharField(max_length=64)

当我要列出所有用户时,我得到:

{
    id: 1,
    name: "name-a",
    memberships: [
        {
            id: 1,
            name: "member-a"
        }, ...
    ]
}

但是我实际上想包括“原因”字段

{
    id: 1,
    name: "name-a",
    memberships: [
        {
            id: 1,
            name: "member-a",
            reason: "somereason"
        }, ...
    ]
}

但是我该如何修改查询集?

User.objects.all().values('members__usermember')

不幸的是...

有人可以支持吗?

编辑:

序列化器:

class UserSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ('id', 'name', 'memberships')

class MembershipSerializer(serializers.ModelSerializer):

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

1 个答案:

答案 0 :(得分:1)

我认为,解决问题的方法与您如何序列化具有查询集本身的对象有关。

您是否正在使用django-rest-framework,如果是,请在响应中添加序列化器。否则,请注释并添加代码以查看如何序列化模型。

编辑以添加可能的序列化器:

尝试与此类似的内容

class UserMembershipSerializer(serializer.ModelSerializer):
    name = serializers.ReadOnlyField(source='membership.name')

    class Meta:
        model = UserMembership
        fields = ('reason', 'name')


class UserSerializer(serializer.ModelSerializer):
    memberships = UserMembershipSerializer(source='usermembership_set', many=True)

    class Meta:
        model = User
        fields = ('id', 'name', 'memberships')