[英]On a django model, how to check uniqueness in the set of values in a ManyToMany field?
For example if I have a set of models like this, how can I make sure that only one Group
instance with the same exact set of Permission
s could exist in the model? 例如,如果我有一组这样的模型,那么如何确保在该模型中只能存在一个具有完全相同的
Permission
集的Group
实例?
class Permission(models.Model):
name = models.CharField(max_length=100, unique=True)
class Group(models.Model):
name = models.CharField(max_length=100, unique=True)
permissions = models.ManyToManyField(Permission)
class User(models.Model):
name = models.CharField(max_length=100, unique=True)
group = models.ForeignKey(Group)
What is the best way to enforce this constraint in django? 在django中强制执行此约束的最佳方法是什么? I don't care about a DB-level constraint.
我不在乎数据库级别的约束。 Does django provide an existing flag on the
ManyToMany
model field or I need to add custom data validation? django是否在
ManyToMany
模型字段上提供现有标记,还是我需要添加自定义数据验证? And if yes, how? 如果是的话,怎么办?
Also I don't use ModelForm
s, so form validation is not what I want. 另外,我不使用
ModelForm
,所以表单验证不是我想要的。
My question is about uniqueness of set of ManyToMany
field relations across the whole model, not in a single instance. 我的问题是关于整个模型(而不是单个实例)中的
ManyToMany
字段关系集的唯一性。
You can override the Group
model's save
method in order to check uniqueness before saving Group
objects. 您可以覆盖
Group
模型的save
方法,以便在保存Group
对象之前检查唯一性。
For example: 例如:
class Group(models.Model):
...
def save(self, *args, **kwargs):
if insert_your_check_here():
super(Group, self).save(*args, **kwargs) # Call the "real" save() method.
else:
return
For more information about overriding predefined model methods take a look at the docs . 有关覆盖预定义模型方法的更多信息,请参阅docs 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.