简体   繁体   English

如何在django模型中初始化与自身无关的ManyToMany字段(对象级别)?

[英]How can I init ManyToMany field in django models that can't relate to itself(object level)?

Example: 例:

class MyUser(models.Model):
    blocked_users = models.ManyToManyField("self", blank=True, null=True)

user = MyUser.object.get(pk=1)
user.blocked_users.add(user)
user.blocked_users.all()[0] == user # (!!!)

Can It be prevented on model/db level? 可以在模型/数据库级别上进行预防吗? Or we need just do check somewhere in app. 或者我们需要在应用程序的某处检查。

Looking at the Django docs for ManyToManyField arguments , it does not seem possible. 查看ManyToManyField参数的Django文档,似乎不可能。

The closest argument to what you want is the limit_choices_to However, that only limits choices on ModelForms and admin (you can still save it like you did in your example), and there is currently no easy way to use it to limit based on another value (pk) in the current model . 你想要的最接近的参数是limit_choices_to但是, 这只限制了ModelForms和admin的选择 (你仍然可以像在你的例子中那样保存它),目前没有简单的方法来使用它来限制基于另一个值(pk)在当前模型中

If you want to prevent it from happening altogether , you'll have to resort to overriding the save method on the through model --something like: 如果你想完全阻止它发生 ,你将不得不求助于覆盖直通模型上的保存方法 -类似于:

class MyUser(models.Model):
    blocked_users = models.ManyToManyField(..., through="BlockedUser")

class BlockedUser(models.Model):
    user = models.ForeignKey(MyUser)
    blocked = models.ForeignKey(MyUser)

    def save(self, *args, **kwargs):
        # Only allow this relationship to be created if 
        if self.user != self.blocked:
            super(BlockedUser, self).save(*args, **kwargs)

You could of course also do this with signals . 你当然也可以用signals做到这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM