开发者

Django 1.1.1, need custom validation dependent on other fields

开发者 https://www.devze.com 2022-12-19 08:14 出处:网络
I have 3 models in a Django app, each one has a \"hostname\" field.For several reasons, these are tracked in different models:

I have 3 models in a Django app, each one has a "hostname" field. For several reasons, these are tracked in different models:

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开发者_StackOverflow社区=45, unique=True, help_text="Name associated with this Virtual IP", verbose_name="name")
...

How can I set up for validation to make sure hostname fields aren't duplicated across any of the 3 models?

I've looked at http://docs.djangoproject.com/en/dev/ref/validators/#ref-validators, but I'm not sure if that's the right path or not. Especially with creating objects from other classes inside a function, etc.


You could use Model Inheritance. Like so:

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)

Don't define BaseDevice as abstract Model.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号