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

发布于 2024-08-20 07:37:50 字数 820 浏览 7 评论 0原文

我的 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,但我不确定这是否是正确的路径。特别是在函数内从其他类创建对象等。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

余生共白头 2024-08-27 07:37:50

您可以使用模型继承。就像这样:

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 定义为抽象模型。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文