Linking models with Foreign Keys – Django Web Development with Python p.9

Welcome to part 9 of the web development with Python and Django tutorial series. In this tutorial, we’re going to work on the organization of tutorials through the use of foreign keys which will allow us to tie certain elements in a database table to another database table’s data.

Text-based tutorials: https://pythonprogramming.net/foreign-keys-django-tutorial/

Channel membership: https://www.youtube.com/channel/UCfzlCWGWYyIQ0aLC5w48gBQ/join
Discord: https://discord.gg/sentdex
Support the content: https://pythonprogramming.net/support-donate/
Twitter: https://twitter.com/sentdex
Facebook: https://www.facebook.com/pythonprogramming.net/
Twitch: https://www.twitch.tv/sentdex
G+: https://plus.google.com/+sentdex

38 comments

  1. Daisy Herd on

    Can you please shout out James McNulty in your next video, he has just gone on a ten minute rant in our computer science lesson about how much he loves you

    Reply
  2. David on

    Regarding migrations, if you can make a migration but you fail to migrate it, you can try to modify it at the APP_NAME/migrations/00XX_auto_XXXXX.py. You can also squash them (AKA reduce or merging them together) with manage.py squashmigrations APP_NAME MIGRATION_NUMBER.

    A migration is just a modification of the current Database on its past migration. If you don’t have anything important, you can delete the migration folder and run makemigrations/migrate again. If you want to save the information you can dumpdata the information into a json and load a jjson with data with…loaddata.

    Managing migrations is pretty messy, so normally google what you need to do or search it at the docs: https://docs.djangoproject.com/en/dev/topics/migrations/

    P.S: Use SlugField and TextField for a Textarea widged for your summary. Django has a lot of fields (some of them related to just one a database, being PostgreSQL the best one).

    Reply
  3. Stéphan Gouin on

    To quickly “roll back” a migration error, can’t you just go in your “Migrations” folder and delete the files you don’t want anymore?

    Reply
  4. Kreig Rastalovich on

    Always look out for sentdex videos for my Django/python info. One thing I originally found a pain to wrap my head around early on was routing for a number of apps using a number of dbs. Be good to see a video on this from your pov.

    Reply
  5. David Clawson on

    Okay, so I might be the only one who didn’t get this or notice it, but it is essential that each series have at least one tutorial. I’m not sure why, maybe I missed something else. It seems like the categories are fine without series, but the series without tutorials seems to cause an Attribute Error: “‘Tutorial’ object has no attribute ‘category_slug'”
    Any ideas why this is so?

    Reply
  6. roman cheprack on

    I have been trying to delete a series or a category and got into an IntegrityError, FOREIGN KEY constraint failed. did someone get
    it also? been looking online for a solution without any luck. suggestions?

    Reply
  7. Jo jo on

    sometimes I get error with migrations, I delete migrations files and the database (make sure not to delete init file) then i do the migrations again. I don’t know really why this happen, same models I repeat the operations then it work!

    Reply
  8. Abdulmajeed Garoot on

    Dude, I lloooove you!! (not in a wrong way) can you teach us how do we store the videos for the tutorials in the database?

    Reply
  9. Anto Anish on

    I did have a problem during the actual migrate where in it said that the main_tutorial with id 1 doesnt have “blah blah” – integrity error – with main_tutorialseries

    I figured this has to be because we have an actual tutorial already in db which is not linked to the tutorial series, which may cause this error.
    So i deleted all migrations from main folder and deleted the db.sqllite3 file.
    Ran make migrations and migrate again and this time it worked.

    Need to create tutorials again and make sure that they are linked to a series or else it will fail during save

    Reply
  10. kevin di on

    After ‘python manage.py migrate’ I got this error : jango.db.utils.IntegrityError: The row in table ‘main_tutorial’ with primary key ‘1’ has an invalid foreign key: main_tutorial.tutorial_series_id contains a value ‘1’ that does not have a corresponding value in main_tutorialseries.id. Who can help me?

    Reply
  11. Dhanunjay Paila on

    I have a requirement to load Excel data to postgres in django. I have created models and loading using pandas dataframe (to_sql). Buy I have a chally here in building relationships between models. As far as I know, we can build relationships if we save model objects one by one using (onetoone, foreign key,manytomany). Please help me how to create relationships when we upload Excel data in one shot

    Reply
  12. Burg on

    I’m getting this error during migration
    File “C:UserspaoloAppDataLocalProgramsPythonPython37-32libsite-packagesdjangodbbackendssqlite3base.py”, line 318, in check_constraints
    bad_value, referenced_table_name, referenced_column_name
    django.db.utils.IntegrityError: The row in table ‘main_tutorial’ with primary key ‘1’ has an invalid foreign key: main_tutorial.tutorial_series_id contains a value ‘1’ that does not have a corresponding value in main_tutorialseries.id.

    Reply
  13. computer engineering Forum on

    FAILS TO MIGRATE AND SHOWS THIS ERROR!!!

    PS C:mysite> python manage.py migrate
    Operations to perform:
    Apply all migrations: admin, auth, contenttypes, main, sessions
    Running migrations:
    Applying main.0003_auto_20190515_2339…Traceback (most recent call last):
    File “manage.py”, line 21, in
    main()
    File “manage.py”, line 17, in main
    execute_from_command_line(sys.argv)
    File “C:UsersfaithAppDataLocalProgramsPythonPython36libsite-packagesdjangocoremanagement__init__.py”,
    e 381, in execute_from_command_line
    utility.execute()
    File “C:UsersfaithAppDataLocalProgramsPythonPython36libsite-packagesdjangocoremanagement__init__.py”,
    e 375, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
    File “C:UsersfaithAppDataLocalProgramsPythonPython36libsite-packagesdjangocoremanagementbase.py”, lin
    3, in run_from_argv
    self.execute(*args, **cmd_options)
    File “C:UsersfaithAppDataLocalProgramsPythonPython36libsite-packagesdjangocoremanagementbase.py”, lin
    4, in execute
    output = self.handle(*args, **options)
    File “C:UsersfaithAppDataLocalProgramsPythonPython36libsite-packagesdjangocoremanagementbase.py”, lin
    , in wrapped
    res = handle_func(*args, **kwargs)
    File “C:UsersfaithAppDataLocalProgramsPythonPython36libsite-packagesdjangocoremanagementcommandsmigr
    py”, line 234, in handle
    fake_initial=fake_initial,
    File “C:UsersfaithAppDataLocalProgramsPythonPython36libsite-packagesdjangodbmigrationsexecutor.py”, l
    117, in migrate
    state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
    File “C:UsersfaithAppDataLocalProgramsPythonPython36libsite-packagesdjangodbmigrationsexecutor.py”, l
    147, in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
    File “C:UsersfaithAppDataLocalProgramsPythonPython36libsite-packagesdjangodbmigrationsexecutor.py”, l
    247, in apply_migration
    migration_recorded = True
    File “C:UsersfaithAppDataLocalProgramsPythonPython36libsite-packagesdjangodbbackendssqlite3schema.py
    ine 34, in __exit__
    self.connection.check_constraints()
    File “C:UsersfaithAppDataLocalProgramsPythonPython36libsite-packagesdjangodbbackendssqlite3base.py”,
    e 318, in check_constraints
    bad_value, referenced_table_name, referenced_column_name
    django.db.utils.IntegrityError: The row in table ‘main_tutorial’ with primary key ‘1’ has an invalid foreign key: ma
    utorial.tutorial_series_id contains a value ‘1’ that does not have a corresponding value in main_tutorialseries.id.
    PS C:mysite>
    PS C:mysite> python manage.py makemigrations
    Migrations for ‘main’:
    mainmigrations005_auto_20190516_2248.py
    – Alter field tutorial_published on tutorial
    PS C:mysite> python manage.py migrate
    Operations to perform:
    Apply all migrations: admin, auth, contenttypes, main, sessions
    Running migrations:
    Applying main.0003_auto_20190515_2339…Traceback (most recent call last):
    File “manage.py”, line 21, in

    main()
    File “manage.py”, line 17, in main
    execute_from_command_line(sys.argv)
    File “C:UsersfaithAppDataLocalProgramsPythonPython36libsite-packagesdjangocoremanagement__init__.py”,
    e 381, in execute_from_command_line
    utility.execute()
    File “C:UsersfaithAppDataLocalProgramsPythonPython36libsite-packagesdjangocoremanagement__init__.py”,
    e 375, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
    File “C:UsersfaithAppDataLocalProgramsPythonPython36libsite-packagesdjangocoremanagementbase.py”, lin
    3, in run_from_argv
    self.execute(*args, **cmd_options)
    File “C:UsersfaithAppDataLocalProgramsPythonPython36libsite-packagesdjangocoremanagementbase.py”, lin
    4, in execute
    output = self.handle(*args, **options)
    File “C:UsersfaithAppDataLocalProgramsPythonPython36libsite-packagesdjangocoremanagementbase.py”, lin
    , in wrapped
    res = handle_func(*args, **kwargs)
    File “C:UsersfaithAppDataLocalProgramsPythonPython36libsite-packagesdjangocoremanagementcommandsmigr
    py”, line 234, in handle
    fake_initial=fake_initial,
    File “C:UsersfaithAppDataLocalProgramsPythonPython36libsite-packagesdjangodbmigrationsexecutor.py”, l
    117, in migrate
    state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
    File “C:UsersfaithAppDataLocalProgramsPythonPython36libsite-packagesdjangodbmigrationsexecutor.py”, l
    147, in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
    File “C:UsersfaithAppDataLocalProgramsPythonPython36libsite-packagesdjangodbmigrationsexecutor.py”, l
    247, in apply_migration
    migration_recorded = True
    File “C:UsersfaithAppDataLocalProgramsPythonPython36libsite-packagesdjangodbbackendssqlite3schema.py
    ine 34, in __exit__
    self.connection.check_constraints()
    File “C:UsersfaithAppDataLocalProgramsPythonPython36libsite-packagesdjangodbbackendssqlite3base.py”,
    e 318, in check_constraints
    bad_value, referenced_table_name, referenced_column_name
    django.db.utils.IntegrityError: The row in table ‘main_tutorial’ with primary key ‘1’ has an invalid foreign key: ma
    utorial.tutorial_series_id contains a value ‘1’ that does not have a corresponding value in main_tutorialseries.id.

    Reply
  14. Jasun Thomas on

    like many on here, I was stuck on the migrations issue and had to troubleshoot it. The models code is solid from what I can tell, and I for the life of me couldn’t get it to work. I ended up following steps to junk the DB entirely, all migrations, then ran makemigrations and migrate again. It was able to get past the process of re-doing the whole thing at once. Of course you then have to run createsuperuser again, and at this point if you’re following this series its not a great loss to do this and run it all together.
    Now my problem is running into adding actual tutorials. I can add series, and categories, but it fails when saving an actual tutorial.
    I’m just now hitting this problem so I haven’t searched very much yet. Anyone else have this issue please pitch in your thoughts. I’ll be back on to share my fix once I get there…

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

Show Buttons
Hide Buttons