jduncan
jduncan

Reputation: 677

Django 1.1.1, need custom validation dependent on other fields

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=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.

Upvotes: 1

Views: 839

Answers (1)

tback
tback

Reputation: 11561

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.

Upvotes: 3

Related Questions