在 Django 中更改多对多关系中的额外字段数据

Change the extra field data in Many-to-many relationship in Django

我与其他字段有多对多关系,我希望能够更改这些字段中的数据(例如友谊状态)。我怎样才能做到这一点?我找到的所有信息都是关于如何读取这些数据的。

class Profile(models.Model):

    # other fields
    friends = models.ManyToManyField("self", blank=True, through='Friendship',
                                    through_fields=('user', 'friend'),
                                    symmetrical=False,
                                    related_name='user_friends')

class Friendship(models.Model):
    user = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='friendships1')
    friend = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='friendships2')
    status = models.PositiveSmallIntegerField(default=0)

    class Meta:
        unique_together = [['user', 'friend']]

我试了这个,但没有用,虽然没有显示错误:

user = User.objects.get(username=request.user)
watched_user = User.objects.get(id=watched_user_id)
Friendship.objects.filter(user=user.profile, friend=watched_user.profile).status = 5
user.save()

我不能调用 Friendship.save() 因为它没有自我。

我也试过了,但没有效果,也没有错误:

user.profile.friends.set([watched_user.profile], through_defaults={'status': 5})
user.save()

这给了我一个没有朋友字段的错误,并向我显示了个人资料字段,而不是友谊字段:

user.profile.user_friends.get(user=user.profile, friend=watched_user.profile).status=5

请帮帮我!

更新:答案有帮助,现在有效!谢谢! 虽然我仍然想知道这是唯一的方法还是也可以从 user.profile 端完成。

您可以使用:

<b>friendship</b> = Friendship.objects.get(
    user=user.profile,
    friend=watched_user.profile
)
friendship<b>.status = 5</b>
friendship<b>.save()</b>

然而,这里可以有 多个 Friendship 在相同的两个用户之间。

我们可以批量更新所有这些友谊:

Friendship.objects.filter(
    user=user.profile,
    friend=watched_user.profile
)<b>.update(status=5)</b>