如何在Django项目中创建模型之间的正确关系

hfyxw5xn  于 2023-02-14  发布在  Go
关注(0)|答案(2)|浏览(97)

我正在使用以下模型开发Django progect:

class Aircraft_fleet(models.Model):
    Aircraft_type = models.CharField(max_length=16)
    Aircraft_Serial_Number = models.CharField(max_length=16)
    Engine_1_Ser_Num = models.ForeignKey('Engine', related_name='Engine_1', on_delete=models.PROTECT)
    Engine_2_Ser_Num = models.ForeignKey('Engine', related_name='Engine_2', on_delete=models.PROTECT)
class Engine(models.Model):
    Ser_Num = models.PositiveIntegerField()
    Flight_Num = models.CharField(max_length=80)
    Flight_Date = models.DateField()
    Oil_Quantity_Departure = models.DecimalField(max_digits=5, decimal_places=2)
    Oil_Quantity_Arrival = models.DecimalField(max_digits=5, decimal_places=2)
    Oil_Temperature_Departure = models.DecimalField(max_digits=5, decimal_places=2)
    Oil_Temperature_Arrival = models.DecimalField(max_digits=5, decimal_places=2)

一架飞机(机队型号)有两个发动机序列号(当然不同)。特定的发动机序列号(发动机型号)只安装在一架特定的飞机上。问题是在数据库中,"发动机"表对每个发动机"序列号"有多个记录。见下图:Engine Model in database look like:
我无法确定如何在这两个模型之间建立适当的关系。
当前关系为一对多,但不起作用,出现以下错误:

django.db.utils.IntegrityError: The row in table 'oilcons_aircraft_fleet' with primary key '1' has an invalid foreign key: oilcons_aircraft_fleet.Engine
_2_Ser_Num_id contains a value '193262' that does not have a corresponding value in oilcons_engine.id.
w6lpcovy

w6lpcovy1#

好的,如果我理解正确的话,engine_ser_num不属于Aircraft_fleet,而是属于Engine
听我说:

class Aircraft_fleet(models.Model):
    Aircraft_type = models.CharField(max_length=16)
    Aircraft_Serial_Number = models.CharField(max_length=16)

class Engine(models.Model):
    aircraft = models.ForeignKey('Aircraft_fleet', on_delete=models.CASCADE)
    Ser_Num = models.PositiveIntegerField()
    Flight_Num = models.CharField(max_length=80)
    Flight_Date = models.DateField()
    Oil_Quantity_Departure = models.DecimalField(max_digits=5, decimal_places=2)
    Oil_Quantity_Arrival = models.DecimalField(max_digits=5, decimal_places=2)
    Oil_Temperature_Departure = models.DecimalField(max_digits=5, decimal_places=2)
    Oil_Temperature_Arrival = models.DecimalField(max_digits=5, decimal_places=2)

现在,一个Engine可以与一个Aircraft_fleet关联

e = Engine.objects.all().first()
print(e.aircraft.Aircraft_type)

一个Aircraft_fleet可以与多个Engine关联

af = Aircraft_fleet.objects.all().first()
for engine in af.engine_set.all():
    print(engine.Ser_num)

告诉我进展如何。

重要编辑:

当然,您需要正确地执行迁移并迁移它,因为IntegrityError也可能是由数据库中仍然具有"旧"关系的"旧"数据引起的。

w8biq8rn

w8biq8rn2#

可能的结构:

class Aircraft(models.Model):
    Aircraft_type = models.CharField(max_length=16)
    Aircraft_Serial_Number = models.CharField(max_length=16)

飞机可能有2/3/4...发动机:
x一个一个一个一个x一个一个二个一个x一个一个三个一个

相关问题