1
votes

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

Image

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.

4
add your insert querysetshafik
Don't call your FK origin_id, call it origin. Then you can use origin_id to assign via PK rather than instance.Daniel Roseman

4 Answers

0
votes

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()
1
votes

Try

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

Have you run python manage.py makemigrations...and migrated the data with python manage.py migrate

0
votes

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 :)