首页 > 解决方案 > 如何将一个 django 模型连接到许多其他模型?

问题描述

我正在尝试开发一个物业管理系统。我已经创建了卧室和浴室模型。在每间卧室和浴室中,我需要添加照明、气候和娱乐模型。我已经创建了这些模型,但我不确定是否应该创建另一个模型,如“Lighting_Bedroom”并使用指向这两个模型的 ForeignKeys,或者是否有其他方法可以做到这一点。

// Bedroom Model
class Bedroom(models.Model):
    type = models.CharField(db_column='Type', choices=BEDROOM_TYPE_CHOICES, max_length=50)
    bed_dimensions = models.CharField(db_column='Bed_Dimension', choices=BED_DIMENSION_CHOICES, max_length=30)
    image = models.ImageField(null=True)
    ensuite = models.BooleanField(default=False)
    notes = models.CharField(db_column='Notes', max_length=500, blank=True, null=True)  # Field name made lowercase.
    property = models.ForeignKey(Property, null=False, on_delete=models.CASCADE)

// Bathroom Model
class Bathroom(models.Model):
    sink = models.CharField(db_column='Sink', choices=SINK_BATHROOM_CHOICES, max_length=50)
    shower = models.CharField(db_column='Shower', choices=SHOWER_BATHROOM_CHOICES, max_length=50)
    tower_rail = models.CharField(db_column='Tower_Rail', choices=TOWER_RAIL_BATHROOM_CHOICES, max_length=50)
    image = models.ImageField(null=True)
    toilet = models.BooleanField(default=False)
    bidet = models.BooleanField(default=False)
    bath = models.BooleanField(default=False)
    extractor_fan = models.BooleanField(default=False)
    notes = models.CharField(db_column='Notes', max_length=500, blank=True, null=True)  # Field name made lowercase.
    property = models.ForeignKey(Property, null=False, on_delete=models.CASCADE)

// Properties

class Lighting(models.Model):
    type = models.CharField(db_column='Type', choices=LIGHTING_TYPE_CHOICES, max_length=30)
    bulb_type = models.CharField(db_column='Bulb_Type',  max_length=30)

class Climatization(models.Model):
    type = models.CharField(db_column='Type', choices=CLIMATIZATION_TYPE_CHOICES, max_length=30)
    use = models.CharField(db_column='Use', choices=CLIMATIZATION_USE_CHOICES, max_length=30)
    brand = models.CharField(db_column='Brand',  max_length=30)
    model = models.CharField(db_column='Model',  max_length=50)
    remote_control = models.BooleanField(default=False)
    notes = models.CharField(db_column='Notes', max_length=500, blank=True, null=True)  # Field name made lowercase.

到目前为止,我还没有创建第三个模型来连接两个模型,因为我已经阅读了有关 ManyToManyField 的信息,但我不确定这是否是我正在寻找的。

标签: pythondjangodatabasedjango-models

解决方案


可以选择在每种房间类型中都有一个RoomFitting模型,OneToOneField然后您的Lighting模型可以具有该模型的外键。

class Bedroom(models.Model):
    fittings = OneToOneField(RoomFitting)

class Lighting(models.Model):
    fitting = ForeignKey(RoomFitting)

这完全取决于该类的使用方式和预期使用方式,例如,并非所有照明都适合在浴室内使用


推荐阅读