views:

283

answers:

1

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")
...

My question is, 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.

Thanks for pointing me in the right direction!

+3  A: 

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.

Till Backhaus
I had thought about that, but the reason I split them all up was because each of the 3 different types of devices have different items that need tracking. Is there a way to this in 1.1.1?
jduncan
the other options is to create a form and a view, and handle the extra validation there, of course. If I can do this within the domain, however, that would be seriously great.
jduncan
if by 'have different items that need tracking' you mean 'have different attributes' then I assume this is exactly what you want. Try to explain what you want to do if I am wrong.
Till Backhaus
Till, no, your model is exactly what I want to do. Thanks!
jduncan