在Django模型保存期间修改ManyToManyField时出现递归错误

0 投票
1 回答
33 浏览
提问于 2025-04-14 15:31

我在使用Django的时候,遇到了一个问题,就是在保存用户时,想要从friends字段中移除用户。

下面是我想法的描述:

每个用户的资料都有一个type,这个type对应着某种等级。比如说,type为X的用户可以有10个朋友,而type为Y的用户可以有20个朋友。

这是我实现的代码:

POWER_OF_PROFILE_TYPE = {"X": 0, "Y": 1}

class ProfileType(models.TextChoices):
    X = "X", "x"
    Y = "Y", "y"

class Profile(models.Model):
    type = models.TextField(choices=ProfileType.choices, default=ProfileType.BASIC, max_length=1)
    friends = models.ManyToManyField(User, blank=True, related_name="friends")
    __currently_type = None

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.__currently_type = self.type_of_profile

    def save(self, *args, **kwargs) -> None:
        if self.type_of_profile != self.__currently_type:
            if POWER_OF_PROFILE_TYPE[self.type_of_profile] < POWER_OF_PROFILE_TYPE[self.__currently_type]:
                users = self.friends.all()[10:]
                self.friends.remove(*users)
                self.save()  # This is causing recursion error

        super().save(*args, **kwargs)
        self.__currently_type = self.type_of_profile


可惜的是,这段代码导致了一个递归错误,提示是RecursionError ...maximum recursion depth exceeded。有人能帮我看看我该怎么做吗?

1 个回答

1

在对多对多字段(M2M)调用.remove()之后,不需要再调用.save()

只要删除导致错误的那一行代码,你就没问题了。

撰写回答