Django 1.1.1,需要依赖于其他字段的自定义验证
我在Django应用程序中有3个模型,每个模型都有一个“主机名”字段。出于以下几个原因,在不同的模型中对这些问题进行了跟踪:Django 1.1.1,需要依赖于其他字段的自定义验证,django,django-models,django-validation,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
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个模型中的任何一个模型中重复
我已经看过了,但我不确定这条路是否正确。尤其是从函数中的其他类创建对象,等等。您可以使用。像这样:
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
模型。我只想指出,Django1.2
中引入了验证器,因此在1.1.1
中不可用,我已经考虑过了,但我之所以把它们分开,是因为这3种不同类型的设备都有不同的需要跟踪的项目。在1.1.1中有没有办法做到这一点?当然,其他选项是创建表单和视图,并在那里处理额外的验证。但是,如果我能在域内做到这一点,那就太好了。如果“有不同的需要跟踪的项目”是指“有不同的属性”,那么我假设这正是你想要的。试着解释一下如果我错了你想做什么。直到,不,你的模型正是我想做的。谢谢