简体   繁体   中英

How to solve django with mysql error in inserting

I create models for MySQL the foreign key constraints always returning error

图片

The model is

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"

and the shell output is

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 manage.py makemigrations...并使用 python manage.py migrate 迁移了数据

You may try this

flight_result=Flight()
flight_result.orgin_id = AirPort.object.first()
flight_result.dest_id = AirPort.object.last()
flight_result.duration = 1000
flight_result.save()

I received this error because I did not see the comma at the end

order.employee=Employee.objects.get(employee_id=x),

Its origin was that I used Order.objects.create() before, for which one uses comma separated attribute assignments and I did not immediately delete the commas. May it help someone who also sat too long in front of the computer :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM