我有一个模型,它与自身有多对多的关系。
我想在模型上创建一个验证,以防止一个组成为它自己的子组,或者它的子组的子组等。目的是防止可能导致循环/无限递归的情况。
我已经尝试在模型 clean() 方法中实现这一点,如下所示。
我还尝试使用事务在模型 save() 方法中实现这一点。
在这两种情况下,我都遇到了无效更改(错误地)保存到数据库的情况,但是如果我尝试对任一实例进行进一步更改,验证会检测到错误,但此时,坏数据已经在数据库中了。
我想知道这是否可能,如果可以,是否可以在模型验证中这样做,所以我不必确保我团队中的每个人都记得从他们将来创建的所有表单中调用这些验证。
事不宜迟,代码:
class Group(models.Model):
name = models.CharField(max_length=200)
sub_groups = models.ManyToManyField('self', through='SubGroup', symmetrical=False)
def validate_no_group_loops(self, seen=None):
if seen is None:
seen = []
if self.id in seen:
raise ValidationError("LOOP DETECTED")
seen.append(self.id)
for sub_group in self.target.all():
sub_group.target.validate_no_group_loops(seen)
# I thought I would use the standard validation mechanism in the clean()
# method, but it appears that when I recurse back to the group I started
# with, I do so with a query to the database which retreives the data before
# it's been modified. I'm still not 100% sure if this is the case, but
# regardless, it does not work.
def clean(self):
self.validate_no_group_loops()
# Suspecting that the problem with implementing this in clean() was that
# I wasn't testing the data with the pending modifications due to the
# repeated queries to the database, I thought that I could handle the
# validation in save(), let the save actually put the bad data into the
# database, and then roll back the transaction if I detect a problem.
# This also doesn't work.
def save(self, *args, **kwargs):
super(Group, self).save(*args, **kwargs)
try:
self.validate_no_group_loops()
except ValidationError as e:
transaction.rollback()
raise e
else:
transaction.commit()
class SubGroup(models.Model):
VERBS = { '+': '+', '-': '-' }
action = models.CharField(max_length=1, choices=VERBS.items(), default='+')
source = models.ForeignKey('Group', related_name='target')
target = models.ForeignKey('Group', related_name='source')
提前感谢您提供的任何帮助。
[编辑] 仅供参考,如果您无法根据我用来管理事务的机制来判断,我目前正在使用 django 1.2,因为这是用于 RHEL6 的 fedora EPEL 存储库中可用的。如果有可用的解决方案但需要升级到 1.3,我升级没有问题。我也在使用 python 2.6.6,因为这是 RedHat 的 RHEL6 中可用的。我宁愿避免 python 升级,但我高度怀疑它是否相关。