Django 1.1.1,需要依赖于其他字段的自定义验证

时间:2010-02-08 21:30:31

标签: django django-models django-validation

我在Django应用程序中有3个模型,每个模型都有一个“主机名”字段。由于几个原因,这些是在不同的模型中跟踪:

class device(models.Model):
...
hostname = models.CharField(max_length=45, unique=True, help_text="The hostname for this device")
...

class netdevice(models.Model):
...
hostname = models.CharField(max_length=45, unique=True, help_text="Name Associated with Device", verbose_name="Hostname")
...

class vipdevice(models.Model):
...
hostname = models.CharField(max_length=45, unique=True, help_text="Name associated with this Virtual IP", verbose_name="name")
...

如何设置验证以确保3个模型中的任何一个都不重复主机名字段?

我看过http://docs.djangoproject.com/en/dev/ref/validators/#ref-validators,但我不确定这是不是正确的道路。特别是在函数内部等其他类中创建对象时

1 个答案:

答案 0 :(得分:3)

您可以使用Model Inheritance。像这样:

class BaseDevice(models.Model): #edit: introduced a base class
    hostname = CharField(max_length=45, unique=True, help_text="The hostname for this device")

class Device(BaseDevice):
    pass

class NetDevice(BaseDevice):
    #edit: added attribute
    tracked_item=models.ForeignKey(SomeItem)

class VipDevice(BaseDevice):
    #edit: added attribute
    another_tracked_item=models.ForeignKey(SomeOtherItem)

不要将BaseDevice定义为abstract模型。