Django约束条件为”字段一在任何行中不等于字段二”?

huangapple go评论57阅读模式
英文:

Django constraint for "field one not in field two for any row"?

问题

假设我有一个Django模型,其中包含两个字段one和two:

class MyModel(models.Model):
    one = models.CharField(max_length=100, unique=True)
    two = models.CharField(max_length=100)

unique=True 表示如果我尝试插入一个具有one="one"的行,而另一个具有相同值的行已经存在,将违反唯一约束。

我应该如何创建一个Django约束,以确保如果存在一个one="one"的行,就不能插入一个two="one"的行?

这似乎与此问题此答案相关,但我没有完全找到答案。

英文:

Suppose I have a Django model with two fields one and two:

class MyModel(models.Model):
    one = models.CharField(max_length=100, unique=True)
    two = models.CharField(max_length=100)

unique=True means if I try to put in a row with one="one" when another such row already exists, a unique constraint will be violated.

How would I make a Django constraint that says if there is a row with one="one", then I can't put in a row with two="one"?

This does seem related to this question and this answer, but I don't quite see the answer to my question.

答案1

得分: 1

models.py
从Hemal Petal提到的,对于这种自定义验证,我发现最好的方法是重写保存方法:

from django.core.exceptions import ValidationError

def save(self, *args, **kwargs):

    if MyModel.objects.filter(
        two=self.one
    ).exists():
        raise ValidationError(f'{self.one} already exists in column two!')
    
    return super().save(*args, **kwargs)
英文:

For custom validation like this I've found it best to override the save method, as @Hemal Petal mentioned:

models.py
from django.core.exceptions import ValidationError

def save(self, *args, **kwargs):

    if MyModel.objects.filter(
        two=self.one
    ).exists():
        raise ValidationError(f'{self.one} already exists in column two!')
    
    return super().save(*args, **kwargs)

huangapple
  • 本文由 发表于 2023年8月4日 06:27:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76831938.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定