Search code examples
djangosqlitemigration

Applying migrations and 'flight.objects.all()' result in an error


In my Django project I encounter errors when trying to apply migrations using python manage.py migrate and flight.objects.all():

from django.db import models

# Create your models here.

class Flight(models.Model):
    origin = models.ForeignKey('airport', on_delete=models.CASCADE, related_name="departure")
    destination = models.ForeignKey('airport', on_delete=models.CASCADE, related_name="arrival")
    duration = models.IntegerField()

    def __str__(self):
        return f"{self.origin} to {self.destination}"

class Airport(models.Model):
    city = models.CharField(max_length=64)
    code = models.CharField(max_length=3)

    def __str__(self):
        return f"{self.city} ({self.code})"

The Flight table had two character fields instead of foreign keys and I had stored a row in it, but later I decided to use Airport table as a foreign key in Flight table. However after I exited the shell and tried to run python manage.py migrate I got an error:

django.db.utils.IntegrityError: The row in table 'flights_flight' with primary key '1' has an invalid foreign key: flights_flight.origin_id contains a value 'Kathmandu' that does not have a corresponding value in flights_airport.id.

It might be because of the previously stored data in Flight table so I tried to delete it, however I can't even view the contents of it. Whenever I try running flight.object.all() I get another error:

django.db.utils.OperationalError: no such column: flights_flight.origin_id

What is the cause of these issues and how to resolve them?


Solution

  • On the basis of your issue, it seems relevant that you had a table named flights_flight in your database. The issue is arising since flights_flight table references the table flights_airport via column origin. This column or field must contain the primary key for airport which is an id field (default if not overidden). Hence, the row in flights_flight table having id=1 has the field origin=Kathmandu which is incorrect. Rather it should have the primary key for the table flights_airport having the city=Kathmandu. Hence, one solution would be to backup the airport table data and flights table data and truncate the table. After applying the migrations, restore the airport data and modify the flights data such that the origin column contains the primary key to the appropriate airport row.

    Hope this solves your problem.