在Django Rest框架中向多对多关系添加新记录

时间:2018-10-02 07:51:52

标签: python django python-3.x django-rest-framework

我试图将新的关系添加到许多记录中,

例如,我有以下模型:

models.py

class Team(models.Model):
    name = models.CharField(blank=True, unique=True, max_length=100)
    players = models.ManyToManyField(User, blank=True, related_name='players')



class TeamInvite(models.Model):
    from_user = models.ForeignKey(User, on_delete=models.DO_NOTHING, related_name='invite_by', blank=True, null=True)
    to_user = models.ForeignKey(User, on_delete=models.DO_NOTHING, related_name='invite_to', blank=True, null=True)
    team = models.ForeignKey(Team, on_delete=models.CASCADE, related_name='invite_to_team', blank=True, null=True)
    status = models.NullBooleanField(blank=True, null=True, default=None,)

和我的序列化器:

serializers.py

class TeamInviteCreateSerializer(serializers.ModelSerializer):
    team = serializers.PrimaryKeyRelatedField(queryset=Team.objects.all())
    from_user = serializers.PrimaryKeyRelatedField(queryset=User.objects.all())
    class Meta:
      model = TeamInvite
      fields = ('id', 'from_user', 'to_user', 'team', 'status')

此后,to_user中将对TeamInvite采取操作的用户,例如接受或拒绝。

我需要序列化程序,它将使用新用户并将其添加到现有团队中,就像以下序列化程序一样:

class TeamInviteAcceptDeclineSerializer(serializers.ModelSerializer):
    method_name = serializers.SerializerMethodField()

    class Meta:
        model = TeamInvite
        fields = ('id', 'from_user', 'date_time', 'team', 'method_name', 'status')

    def get_method_name(self, *args, **kwargs):
        method_name = None  # kwargs['context']['request'].method_name
        return method_name

    def update(self, instance, validated_data):
        instance.team = validated_data.get('team', instance.team)
        method_name = validated_data.get('method_name')
        instance.status = validated_data.get('status', instance.status)
        instance.to_user = validated_data.get('to_user', instance.to_user)

        if method_name == 'decline':
            instance.status = False
        else:
            instance.status = True
            team = Team.objects.get(pk=instance.team.pk)
            team.players.add(instance.to_user)
            # team.players.create(team_id=team, user_id=instance.to_user)
            team.save()
        instance.save()
        return instance

update函数不会将用户添加到现有团队,也不会引发任何错误。我在这里想念什么?

我的要求是:

{
    "from_user": 1,
    "to_user": 23
    "team": 64,
    "method_name": "accept",
    "status": null
}

谢谢

1 个答案:

答案 0 :(得分:0)

我在代码中遗漏了点.. 它在:

class TeamInviteAcceptDeclineSerializer(serializers.ModelSerializer):
    method_name = serializers.SerializerMethodField()

    class Meta:
        model = TeamInvite
        fields = ('id', 'from_user', 'date_time', 'team', 'method_name', 'status')

fields =错过了“ to_user”婴儿车