gpt4 book ai didi

python - 如何解决django插入mysql报错

转载 作者:行者123 更新时间:2023-11-29 07:25:23 24 4
gpt4 key购买 nike

我为 MySQL 的外键创建模型约束总是返回错误

Image

模型是

class AirPort(models.Model):

code = models.CharField(max_length=3)
city = models.CharField(max_length=100)

def __str__(self):
return f"{self.id} - CODE =>{self.code} :: CITY=> {self.city}"

class Flight(models.Model):

orgin_id = models.ForeignKey(AirPort,on_delete=models.CASCADE,related_name="dep")
dest_id = models.ForeignKey(AirPort,on_delete=models.CASCADE,related_name="arrival")
duration = models.IntegerField()

def __str__(self):
return f"{self.id} - {self.orgin} TO {self.dest} will take {self.duration} minutes"

shell输出是

a=Flight(orgin_id=1,dest_id=2,duration=120) Traceback (most recent call last): File "", line 1, in File "/home/kid/PycharmProjects/hardward/venv/lib/python3.6/site-packages/django/db/models/base.py", line 467, in init _setattr(self, field.name, rel_obj) File "/home/kid/PycharmProjects/hardward/venv/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 210, in set self.field.remote_field.model._meta.object_name, ValueError: Cannot assign "1": "Flight.orgin_id" must be a "AirPort" instance.

最佳答案

尝试

a=Flight(orgin=AirPort.object.get(id=1),dest=AirPort.object.get(id=2),duration=120)

关于python - 如何解决django插入mysql报错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54103267/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com