[Fixed]-Django REST Framework tutorial, OperationalError: table snippets_snippet has no column named owner_id

1👍

First of all, you have not provided a value for ‘owner’ while saving a Snippet object. You need to do something like this:

from django.contrib.auth.models import User
new_user = User.objects.create(...)
snippet = Snippet(owner=new_user, code='foo = "bar"\n')
snippet.save()

Nevertheless, it doesn’t explain why the owner_id column was not created. Can you change the model to something like this and see if it detects the owner column?

from django.contrib.auth.models import User

class Snippet(models.Model):
    owner = models.ForeignKey(User, related_name='snippets')
    ...

Then run these steps to attempt to create the column.

python manage.py makemigrations snippets
python manage.py migrate

0👍

It looks like you didn’t delete the original database.

The tutorial removes it after the model is changed:

rm -f tmp.db db.sqlite3
rm -r snippets/migrations
python manage.py makemigrations snippets
python manage.py migrate

If you did remove none of the tmp.db or db.sqlite3 then Django might think it has already done the migration and will not redo it.

Make sure you find one of the two aforementioned files and remove them and then run the above script (plus the createsuperuser for you to login in).

Leave a comment