【问题标题】:Django: How to make model attribute dependent on foreign key present in that modelDjango:如何使模型属性依赖于该模型中存在的外键
【发布时间】:2020-07-03 18:13:28
【问题描述】:

我在 Django 中有两个模型:State 和 City

class State(models.Model):
    #regex = re.compile(r'^[a-zA-Z][a-zA-Z ]+[a-zA-Z]$', re.IGNORECASE)
    name_regex = RegexValidator(regex=r'^[a-zA-Z]+$',
                                message="Name should only consist of characters")
    name = models.CharField(validators=[name_regex], max_length=100, unique=True)

class City(models.Model):
    state = models.ForeignKey('State', on_delete=models.SET_NULL, null=True)
    name_regex = RegexValidator(regex=r'^[a-zA-Z]+$',
                                message="Name should only consist of characters")
    name = models.CharField(validators=[name_regex], max_length=100, unique=True)
    postalcode = models.IntegerField(unique=True)

在城市模型中,我有属性状态,它是状态模型的外键。在城市模型中,我想让属性名称依赖于州属性,因为一个州将有一个同名的城市,但一个城市名称可以在多个州。 就像乌代浦尔市在印度的拉贾斯坦邦和北方邦都存在,但拉贾斯坦邦将有一个城市作为乌代浦尔。

【问题讨论】:

  • 依赖是什么意思?你说的是验证吗?
  • 是的,如果我们可以在应用“POST”方法时进行任何验证?

标签: django django-models django-rest-framework django-views foreign-keys


【解决方案1】:

听起来您需要在 City 模型上使用 unique_together 约束:https://docs.djangoproject.com/en/2.2/ref/models/options/#unique-together

类似这样的:

class City(models.Model):
    state = models.ForeignKey('State', on_delete=models.SET_NULL, null=True)
    name_regex = RegexValidator(regex=r'^[a-zA-Z]+$',
                                message="Name should only consist of characters")
    name = models.CharField(validators=[name_regex], max_length=100, unique=True)
    postalcode = models.IntegerField(unique=True)

    class Meta:
        unique_together = ["state", "name"]

【讨论】:

  • 嘿,这可以通过从名称字段中删除“unique=True”来实现。但是现在我也遇到一个问题,即大写和小写的字段名称被认为是不同的。我希望 Udaipur/udaipur/udaiPur 都应该被视为相同。那么如何实现呢?
猜你喜欢
  • 2012-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-15
  • 1970-01-01
  • 2018-12-02
  • 2019-03-18
  • 2014-07-02
相关资源
最近更新 更多