防止Django中的外键排列 [英] Prevent permutations of foreign keys in Django
问题描述
我有一个django模型如下:
class ModelName(models.Model):
field_one = models .ForeignKey(Table_One,related_name =field_one)
field_two = models.ForeignKey(Table_One,related_name =field_two)
我知道 unique_together
可以用来确保重复条目不能被创建。
例如,如果上表:
unique_together = [ 'field_one','field_two']
然后,您可以输入
field_one
和 B
field_two
。但是,您不能再次进行相同的输入。但是这也允许为 field_one
和 A
输入 B
field_two
,根据我的控制器逻辑与 A和B
相同。
我需要确保如果为各个字段输入A和B,则无法再次输入B和A。
如何仅允许独特组合的条目?
样本干净的验证码
from django.db.models import Q
pre>
def clean(self):
mn = ModelName.objects.filter(Q(field_one = self.field_one,field_two = field_two) | Q(field_one = self.field_two,field_two = field_one))
如果mn.exists():
raise ValidationError('已经存在')
I have a django Model as follows:
class ModelName(models.Model): field_one = models.ForeignKey(Table_One, related_name="field_one") field_two = models.ForeignKey(Table_One, related_name="field_two")
I know
unique_together
can be used to make sure duplicate entries cant be made.Eg, if for the above table:
unique_together = ['field_one', 'field_two']
Then you can enter values such as
A
forfield_one
andB
forfield_two
. However, you cannot make the same entry again. But this also allows entryB
forfield_one
andA
forfield_two
, which according to my controller logic is the same asA and B
.I need to make sure that if A and B are entered for the respective fields, B and A cannot be entered again.
How do I allow only entries of unique combinations?
解决方案Sample clean validation code,
from django.db.models import Q def clean(self): mn = ModelName.objects.filter(Q(field_one=self.field_one,field_two=field_two)|Q(field_one=self.field_two,field_two=field_one)) if mn.exists(): raise ValidationError('Already exist')
这篇关于防止Django中的外键排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!