根据模型中的数据添加Django约束

时间:2020-08-22 21:11:29

标签: python django django-models

说我有一个像这样的简单模型:

class Country:
    name = models.CharField(max_length=200, unique=True)

class City:
    name = models.CharField(max_length=200, unique=True)
    country = models.ForeignField('Country', on_delete=models.PROTECT)

class Hat:
    name = models.CharField(max_length=200, unique=True)
    country = models.ForeignField('Country', on_delete=models.PROTECT)

class Person:
    name = models.CharField(max_length=200, unique=True)
    country = models.ForeignField('Country', on_delete=models.PROTECT)
    city = models.ForeignField('City', on_delete=models.PROTECT)
    hat = models.ForeignField('Hat', on_delete=models.PROTECT)

在这个人为的示例中,帽子只能在一个国家/地区佩戴,城市也只能在一个国家/地区佩戴。但是,一个人必须准确分配一顶帽子和一个城市。这样,一个人的帽子和城市必须与该人所在的国家/地区相同。

在city字段中,使用limit_choices_to看不到任何简单的方法,因为它无法引用当前数据值。

解决此问题的最佳方法是什么-理想情况下也可以与管理控制台一起使用?

0 个答案:

没有答案
相关问题