防止Django中的外键排列 [英] Prevent permutations of foreign keys in Django

查看:108
本文介绍了防止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 

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('已经存在')
pre>

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 for field_one and B for field_two. However, you cannot make the same entry again. But this also allows entry B for field_one and A for field_two, which according to my controller logic is the same as A 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆