Vicent LHK ROT
Vicent LHK ROT

Reputation: 31

Django: unable to save a value in models

I am currently working on a CS50 Web development SQL, Models, and Migrations and following what the tutorial says to do , yet I found that I am not able to duplicate the result at some points.

I have created a new class in models.py named Airport.

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

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

When I try to use the f = Airport(code="NY", city="New York") f.save() function to save it, the following error occurs

django.db.utils.OperationalError: no such table: flights_airport

I have checked some solutions from the internet, the first one is to do the migration again. Yet, when I do python manage.py makemigrations it says

No changes detected

when I do python manage.py migrate, it shows a long error message with

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 'new york' that does not have a corresponding value in flights_airport.id

I have also tried to delete all the data with Airport.objects.all().delete()

It again shows the following error code

django.db.utils.OperationalError: no such table: flights_airport

I am stuck in a point that I cant do migration nor can I start it again. I'd like to know what shall I do

Upvotes: 1

Views: 713

Answers (4)

eifcgn24
eifcgn24

Reputation: 23

I had exactly the same problem. The issue seems to be that after creating a Model Class "Flight", the tutorial instructed us to save some flight data in the database (and not delete it). Then we created an "Airport" class and adjusted the "Flight" class to contain a Foreign Key from the "Airport" class/database, which was empty. So it seems that when doing the migraiton the existing data could not be assigned to a foreign key. Deleting the data from the "flights" table solves the problem.

Upvotes: 1

Mattia Peracchi
Mattia Peracchi

Reputation: 58

This means that there is a row in your DB in the table flights_flights that has an external key that tries to find in the table flights_airport a row with flights_flight.origin_id == "new york", which doesn't exists, hence it can't perform the migration correctly. Simply deleting the incriminating row in the flights table should allow you to fix this.

Upvotes: 0

Yousef Alm
Yousef Alm

Reputation: 238

Make sure the app is included in settings.

Then run python manage.py makemigrations flights

And python manage.py migrate flights

Upvotes: 0

Ali Irani
Ali Irani

Reputation: 607

First, clear your DB with this command to completely refresh your DB rows.

python manage.py sqlflush # needs django above 1.9

Then, again

python manage.py makemigration
python manage.py migrate

Upvotes: 0

Related Questions