【问题标题】:Django models relations: connect field to instances of itselfDjango 模型关系:将字段连接到自身的实例
【发布时间】:2022-01-07 23:11:00
【问题描述】:

我正在创建一个网络设备跟踪器,我希望接口仅在某些条件下相互连接。然而,我试图将接口连接在一起。我认为我的模型逻辑不正确,因为在 InterfaceConnection 我将接口连接到设备,而不是另一个接口。

from django.db import models
from django.core.exceptions import ValidationError
from .constants import ROLES, FORM_FACTORS


class Device(models.Model):
    hostname = models.CharField(max_length=200, unique=True, blank=False, null=False)
    ip_address = models.GenericIPAddressField(blank=False, null=False)
    role = models.CharField(max_length=20, choices=ROLES, blank=False, null=False)

    def __str__(self) -> str:
        return f"Device #{self.id} - hostname {self.hostname}"


class Interface(models.Model):
    device = models.ForeignKey(to=Device, to_field="hostname", on_delete=models.CASCADE, related_name="interface")
    name = models.CharField(max_length=200, blank=False, null=False)
    form_factor = models.CharField(max_length=10, choices=FORM_FACTORS, blank=False, null=False)

    def __str__(self) -> str:
        return f"Interface #{self.id} - {self.name}"


class InterfaceConnection(models.Model):
    interface = models.ForeignKey(to=Interface, blank=True, null=True, 
        on_delete=models.CASCADE, related_name="interface_connection")
    device = models.ForeignKey(to=Device, blank=False, null=False, 
        on_delete=models.CASCADE, related_name="interface_connection")
    
    def clean(self) -> None:
        if self.interface and self.interface.form_factor == 'virtual':
            raise ValidationError({
                "interface":
                "virtual interface cannot be connected to any other interface"
            })
        return super().clean()

    class Meta:
        unique_together = ("interface", "device")
    
    def __str__(self) -> str:
        return f"Connection #{self.id} - interface {self.interface.name} - device {self.device.hostname}"

我该如何表达这种关系?我感谢任何见解。

【问题讨论】:

    标签: python django django-models orm


    【解决方案1】:

    您可以通过引用模型名称或使用关键字 'self' 来自引用模型。

    class Interface(models.Model):
        connected_interface = models.ForeignKey('Interface', blank=True, null=True, on_delete=models.CASCADE, related_name="interface_connection")
    

    或

    class Interface(models.Model):
        connected_interface = models.ForeignKey('self', blank=True, null=True, on_delete=models.CASCADE, related_name="interface_connection")
    

    【讨论】:

    • 您好,谢谢您的回答!这是否意味着我不再需要 InterfaceConnection?
    • @MurphyAdam,这取决于很多事情,例如您是否要向连接添加其他数据(现在,如果您摆脱 InterfaceConnection 模型,您不会丢失任何信息)和一般设计偏好.如果您想使用单独的 InterfaceConnection 模型,我只需定义两个字段 interface_1 和 interface_2。然后这两个将形成一个连接。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-20
    • 1970-01-01
    • 1970-01-01
    • 2011-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多