Django ProgrammingError in Fields on PostgreSQL - django

models.py
class Stop(models.Model):
idn = models.PositiveIntegerField(primary_key=True, unique=True)
label = models.CharField(null=False, blank=False, max_length=512)
coor_x = models.FloatField()
coor_y = models.FloatField()
buses = models.ManyToManyField(Bus)
latest_query_datetime = models.DateTimeField(default=datetime(2000, 1, 1, 0, 0, 0))
latest_query_data = JSONField(default={})
class Meta:
ordering = ["label"]
def __str__(self):
return self.label
When I run:
python3 manage.py makemigrations && python3 manage.py migrate
It raises a ProgrammingError saying that jsonb datatype does not exist:
Migrations for 'rest':
0007_auto_20160612_1301.py:
- Alter field latest_query_data on stop
Operations to perform:
Apply all migrations: contenttypes, rest, auth, sessions, admin
Running migrations:
Rendering model states... DONE
Applying rest.0005_auto_20160612_1237...Traceback (most recent call last):
File "/home/erayerdin/.venv/eshot-api/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
psycopg2.ProgrammingError: type "jsonb" does not exist
LINE 1: ... TABLE "rest_stop" ADD COLUMN "latest_query_data" jsonb DEFA...
^
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/home/erayerdin/.venv/eshot-api/lib/python3.5/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line
utility.execute()
File "/home/erayerdin/.venv/eshot-api/lib/python3.5/site-packages/django/core/management/__init__.py", line 345, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/erayerdin/.venv/eshot-api/lib/python3.5/site-packages/django/core/management/base.py", line 348, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/erayerdin/.venv/eshot-api/lib/python3.5/site-packages/django/core/management/base.py", line 399, in execute
output = self.handle(*args, **options)
File "/home/erayerdin/.venv/eshot-api/lib/python3.5/site-packages/django/core/management/commands/migrate.py", line 200, in handle
executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial)
File "/home/erayerdin/.venv/eshot-api/lib/python3.5/site-packages/django/db/migrations/executor.py", line 92, in migrate
self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_initial)
File "/home/erayerdin/.venv/eshot-api/lib/python3.5/site-packages/django/db/migrations/executor.py", line 121, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
File "/home/erayerdin/.venv/eshot-api/lib/python3.5/site-packages/django/db/migrations/executor.py", line 198, in apply_migration
state = migration.apply(state, schema_editor)
File "/home/erayerdin/.venv/eshot-api/lib/python3.5/site-packages/django/db/migrations/migration.py", line 123, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "/home/erayerdin/.venv/eshot-api/lib/python3.5/site-packages/django/db/migrations/operations/fields.py", line 62, in database_forwards
field,
File "/home/erayerdin/.venv/eshot-api/lib/python3.5/site-packages/django/db/backends/base/schema.py", line 396, in add_field
self.execute(sql, params)
File "/home/erayerdin/.venv/eshot-api/lib/python3.5/site-packages/django/db/backends/base/schema.py", line 110, in execute
cursor.execute(sql, params)
File "/home/erayerdin/.venv/eshot-api/lib/python3.5/site-packages/django/db/backends/utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/home/erayerdin/.venv/eshot-api/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/home/erayerdin/.venv/eshot-api/lib/python3.5/site-packages/django/db/utils.py", line 95, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/home/erayerdin/.venv/eshot-api/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/home/erayerdin/.venv/eshot-api/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: type "jsonb" does not exist
LINE 1: ... TABLE "rest_stop" ADD COLUMN "latest_query_data" jsonb DEFA...
I use PostgreSQL to use JSONField and update it when a user requests a view. If I do not use default={}, it tells me to make one.
Further Analysis
I changed latest_query_data field to TextField so that I can store as string and convert to dict when I need. However, this also raised the same error.
Environment
django 1.9.6
psycopg 2.6.1

According to the Django docs, JSONField requires PostgreSQL ≥ 9.4 and Psycopg2 ≥ 2.5.4
What PostgreSQL version are you using?
See https://docs.djangoproject.com/en/dev/ref/contrib/postgres/fields/#django.contrib.postgres.fields.JSONField
Ubuntu 14.04 repositories contain only 9.3 version. You can review this to upgrade your version.

Based on the Anonymous comment, I found the following to work:
from django.contrib.postgres import fields
class OldJSONField(fields.JSONField):
def db_type(self, connection):
return 'json'
class Stop(models.Model):
...
latest_query_data = OldJSONField(default=dict)
...

If you are getting this error and you have installed Postgres > 9.4 then I would check that you aren't connecting to an older version of Postgres that is also installed on your instance.
To confirm what you are connecting to from Django you can use psycopg2 from the shell:
import psycopg2
conn = psycopg2.connect("dbname=<your database> user=<your user> password=<your password>")
cur = conn.cursor()
cur.execute("SELECT Version();")
cur.fetchone()
Make sure the version here is > 9.4. If not you probably have a couple of versions installed and your service configuration is pointing at the other version.

With older versions of PostgreSQL for example "PostgreSQL9.2.x",
We can use an alternative as
from jsonfield import JSONField
instead of:
from django.contrib.postgres.fields import JSONField
for example:
from django.db import models
from jsonfield import JSONField
class MyModel(models.Model):
json = JSONField()
Can install as:
pip install jsonfield
Check this out:
Add support for PostgreSQL 9.2+'s native json type. #32
This solution is especially good for some limited edition versions. For example,
on VPS & Cpanel that supports postgresql9.2 by default
more details!, see"rpkilby-jsonfield"

So, it seems a bug on psycopg2 or django, I will post an issue on both repositories. This is how I've solved (at least, ProgrammingError) the problem.
Change JSONField to TextField.
Flush your database.
Beware! This operation will erase all the data but the structure in your database.
Remove all migrations folder in all of your apps.
Run python3 manage.py makemigrations && python3 manage.py migrate in all of your apps.
Run python manage.py makemigrations <appname> && python3 manage.py migrate <appname> for each app you have.
Use built-in json module to convert between str and dict.
However, remember, this solution requires so much effort if you want to filter a QuerySet of a model. I do not recommend it, but there was no other solution to get rid of this error and all I needed to do was to save data and represent it.
! This answer will be accepted as default if there will not occur any other better solution in 48 hours.

Related

Django error relation "auth_user" does not exist using multiple database

I'm working on Django 1.9 and python 3.3 project using multiple databases (different schema in a same postgresql database). When I try to migrate the project for the first time, I'm getting this error
Running migrations:
Rendering model states... DONE
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying MyApp.0001_initial...Traceback (most recent call last):
File "/usr/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
psycopg2.ProgrammingError: ERROR: relation "auth_user" does not exist
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 10, in
execute_from_command_line(sys.argv)
File "/usr/lib/python3.4/site-packages/django/core/management/__init__.py", line 350, in execute_from_command_line
utility.execute()
File "/usr/lib/python3.4/site-packages/django/core/management/__init__.py", line 342, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/lib/python3.4/site-packages/django/core/management/base.py", line 348, in run_from_argv
self.execute(*args, **cmd_options)
File "/usr/lib/python3.4/site-packages/django/core/management/base.py", line 399, in execute
output = self.handle(*args, **options)
File "/usr/lib/python3.4/site-packages/django/core/management/commands/migrate.py", line 200, in handle
executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial)
File "/usr/lib/python3.4/site-packages/django/db/migrations/executor.py", line 92, in migrate
self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_initial)
File "/usr/lib/python3.4/site-packages/django/db/migrations/executor.py", line 121, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
File "/usr/lib/python3.4/site-packages/django/db/migrations/executor.py", line 198, in apply_migration
state = migration.apply(state, schema_editor)
File "/usr/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 90, in __exit__
self.execute(sql)
File "/usr/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 110, in execute
cursor.execute(sql, params)
File "/usr/lib/python3.4/site-packages/django/db/backends/utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/usr/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/usr/lib/python3.4/site-packages/django/db/utils.py", line 95, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/usr/lib/python3.4/site-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/usr/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: ERROR: relation "auth_user" does not exist
This error seems to appeard in other projects when the auth_user table isn't migrated. In my case beginning my migration with manage.py migrate auth before migrating the app who need it doesn't solve the problem.
I suspect that the problem come from the use of different database in Django. My auth_user table is stored in the default database and the content of the models.py is routed to an other database.
Is the migration process looking for the auth_user table in the same database than my app database? Is it something absolutely different?
Answer to the problem
It is in fact a cross database reference problem. Django can't create cross database foreign keys.
From the Django 1.8 documentation (and there isn't any solution in the next versions (current version is 1.10)) :
Cross-database relations
Django doesn’t currently provide any support for foreign key or
many-to-many relationships spanning multiple databases. If you have
used a router to partition models to different databases, any foreign
key and many-to-many relationships defined by those models must be
internal to a single database.
This is because of referential integrity. In order to maintain a
relationship between two objects, Django needs to know that the
primary key of the related object is valid. If the primary key is
stored on a separate database, it’s not possible to easily evaluate
the validity of a primary key.
If you’re using Postgres, Oracle, or MySQL with InnoDB, this is
enforced at the database integrity level – database level key
constraints prevent the creation of relations that can’t be validated.
However, if you’re using SQLite or MySQL with MyISAM tables, there is
no enforced referential integrity; as a result, you may be able to
‘fake’ cross database foreign keys. However, this configuration is not
officially supported by Django
How to workaround and keep separate databases
In my case, because router are working, there is a little hack to simplify the cross database objects.
class CrossDBUser(models.Model):
user = models.IntegerField()
def get_user(self):
return User.objects.get(id=self.user)
def set_user(self, user):
self.user = user.id
class MyClassWithCrossDB(CrossDBUser):
field1 = models.CharField(max_length=200, blank=False)
field2 = models.IntegerField(default=0)
With this I can use the method set_user and get_user to work with the user stored in my object MyClassWithCrossDB.
Of course it's not perfect because it doesn't allow automated actions like on_delete=models.CASCADE and I'm obliged to work with methods instead of the instance variable. But it is a solution to workaround.

Does makemigrations in django recreates existing tables for a reason?

I wanted to validate if there is a bug in makemigrations in django 1.8 with sql lite or I am doing something wrong.
After I Dropped my DB and deleted all migration folders. I run
python manage.py makemigrations
python manage.py migrate
DB gets created no problems.
2.I have to modify existing model in one of the apps (app abc)
I perform my change and run again
python manage.py makemigrations
3.it doesn't find any changes
then I run same thing again but with app name
python manage.py makemigrations abc
4.It does some updates in migrations , I believe it recreates all the tables and not just my change !!!!
5.Then I execute
python manage.py migrate
and getting error that table already exists .
Is it a bug in django framework or I am doing something wrong and there is a reason why it behaves this way?
Copy paste from my shell starting from step 2:
(mrp) C:\Users\I812624\dev\mrp\src>python manage.py makemigrations
No changes detected
(mrp) C:\Users\I812624\dev\mrp\src>python manage.py makemigrations purchase
Migrations for 'purchase':
0001_initial.py:
- Create model PO
- Create model POmaterial
(mrp) C:\Users\I812624\dev\mrp\src>python manage.py migrate
Operations to perform:
Synchronize unmigrated apps: customer, manufacture, product, django_filters, a
utofixture, staticfiles, messages, smart_selects, watson, sales, item, django_co
untries, mptt, inventory, django_select2, production, main, crispy_forms
Apply all migrations: purchase, vendor, sessions, admin, sites, flatpages, con
tenttypes, auth, registration
Synchronizing apps without migrations:
Creating tables...
Running deferred SQL...
Installing custom SQL...
Running migrations:
Rendering model states... DONE
Applying purchase.0001_initial...Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "C:\Users\I812624\dev\mrp\lib\site-packages\django\core\management\__init
__.py", line 338, in execute_from_command_line
utility.execute()
File "C:\Users\I812624\dev\mrp\lib\site-packages\django\core\management\__init
__.py", line 330, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\I812624\dev\mrp\lib\site-packages\django\core\management\base.p
y", line 390, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\I812624\dev\mrp\lib\site-packages\django\core\management\base.p
y", line 441, in execute
output = self.handle(*args, **options)
File "C:\Users\I812624\dev\mrp\lib\site-packages\django\core\management\comman
ds\migrate.py", line 221, in handle
executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial)
File "C:\Users\I812624\dev\mrp\lib\site-packages\django\db\migrations\executor
.py", line 110, in migrate
self.apply_migration(states[migration], migration, fake=fake, fake_initial=f
ake_initial)
File "C:\Users\I812624\dev\mrp\lib\site-packages\django\db\migrations\executor
.py", line 147, in apply_migration
state = migration.apply(state, schema_editor)
File "C:\Users\I812624\dev\mrp\lib\site-packages\django\db\migrations\migratio
n.py", line 115, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, projec
t_state)
File "C:\Users\I812624\dev\mrp\lib\site-packages\django\db\migrations\operatio
ns\models.py", line 59, in database_forwards
schema_editor.create_model(model)
File "C:\Users\I812624\dev\mrp\lib\site-packages\django\db\backends\base\schem
a.py", line 282, in create_model
self.execute(sql, params or None)
File "C:\Users\I812624\dev\mrp\lib\site-packages\django\db\backends\base\schem
a.py", line 107, in execute
cursor.execute(sql, params)
File "C:\Users\I812624\dev\mrp\lib\site-packages\django\db\backends\utils.py",
line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "C:\Users\I812624\dev\mrp\lib\site-packages\django\db\backends\utils.py",
line 64, in execute
return self.cursor.execute(sql, params)
File "C:\Users\I812624\dev\mrp\lib\site-packages\django\db\utils.py", line 97,
in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "C:\Users\I812624\dev\mrp\lib\site-packages\django\db\backends\utils.py",
line 62, in execute
return self.cursor.execute(sql)
File "C:\Users\I812624\dev\mrp\lib\site-packages\django\db\backends\sqlite3\ba
se.py", line 316, in execute
return Database.Cursor.execute(self, query)
django.db.utils.OperationalError: table "purchase_po" already exists
To answer my own question .
So what I have figured out . I believe the problem is that I have originally deleted the folders migrations and when I run makemigrations without specifying particular app it does create a DB but it dosent create the folder makemigrations with ____init____.py inside it.
solution each time when you drop db and delete migrations folder for whatever reason dont just delete the migrations folder but only its content excluding init file.
Or when you do delete the folder run make migrations individually for each app as #MicroPyramid suggested.
Without doing deeper investigation it looks to me or as confusing designed behaviour or a bug from Django side.

django 1.9: ProgrammingError: relation "users_user" does not exist

I am running into a ProgrammingError when doing migrate, I think it may be related to the use of django-allauth with a custom user. Here is what I do
1/ Create a fresh database with psql:
create database dj_example;
2/ Installed_apps contain django.contrib.sites:
DJANGO_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
)
THIRD_PARTY_APPS = (
'crispy_forms', # Form layouts
'allauth', # registration
'allauth.account', # registration
#'allauth.socialaccount', # registration
#'allauth.socialaccount.providers.twitter',
'djcelery', #Celery
)
LOCAL_APPS = (
'tucat.users', # custom users app
}
3/ site_id is set to 1
SITE_ID = 1
4/ Custom user model is overly simple:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
def __unicode__(self):
return self.username
5/ Makemigrations works fine
# python manage.py makemigrations
Migrations for 'djcelery':
0028_auto_20160601_1919.py:
- Alter field status on taskmeta
6/ Migrate returns ProgrammingError: relation "users_user" does not exist
# python manage.py migrate
Operations to perform:
Apply all migrations: auth, contenttypes, djcelery, account, admin, sessions
Running migrations:
Rendering model states... DONE
Applying account.0001_initial...Traceback (most recent call last):
File "/home/antoinet/.virtualenvs/tucat/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
psycopg2.ProgrammingError: relation "users_user" does not exist
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 12, in <module>
execute_from_command_line(sys.argv)
File "/home/antoinet/.virtualenvs/tucat/lib/python3.4/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line
utility.execute()
File "/home/antoinet/.virtualenvs/tucat/lib/python3.4/site-packages/django/core/management/__init__.py", line 345, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/antoinet/.virtualenvs/tucat/lib/python3.4/site-packages/django/core/management/base.py", line 348, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/antoinet/.virtualenvs/tucat/lib/python3.4/site-packages/django/core/management/base.py", line 399, in execute
output = self.handle(*args, **options)
File "/home/antoinet/.virtualenvs/tucat/lib/python3.4/site-packages/django/core/management/commands/migrate.py", line 200, in handle
executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial)
File "/home/antoinet/.virtualenvs/tucat/lib/python3.4/site-packages/django/db/migrations/executor.py", line 92, in migrate
self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_initial)
File "/home/antoinet/.virtualenvs/tucat/lib/python3.4/site-packages/django/db/migrations/executor.py", line 121, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
File "/home/antoinet/.virtualenvs/tucat/lib/python3.4/site-packages/django/db/migrations/executor.py", line 198, in apply_migration
state = migration.apply(state, schema_editor)
File "/home/antoinet/.virtualenvs/tucat/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 90, in __exit__
self.execute(sql)
File "/home/antoinet/.virtualenvs/tucat/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 110, in execute
cursor.execute(sql, params)
File "/home/antoinet/.virtualenvs/tucat/lib/python3.4/site-packages/django/db/backends/utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/home/antoinet/.virtualenvs/tucat/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/home/antoinet/.virtualenvs/tucat/lib/python3.4/site-packages/django/db/utils.py", line 95, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/home/antoinet/.virtualenvs/tucat/lib/python3.4/site-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/home/antoinet/.virtualenvs/tucat/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "users_user" does not exist
Any idea of how to resolve that problem?
You have to delete the migrations folder and then, you should do
python manage.py migrate --run-syncdb
python manage.py migrate --fake appname
Your error is caused by the order you run the migrations. Since many apps depend on the user model existing, you must run the initial migrations for your custom user app before those other apps.
If you change the default user model in an existing project, it might be easier to discard all existing migrations (and the database) and rebuild from scratch. The order to apply migrations would be:
The core django.contrib apps.
Your custom user app.
Other custom apps and third party apps.
You can use django-admin showmigrations to see which migrations exists and are planned.
FYI-
I had this problem, and to resolve it I had to comment out all references to views.py in my urls.py and url_tenants.py files. Then, I ran makemigrations and got the database tables to create, then run migrate_schemas, and later uncomment the url files. Hope this helps someone.

Recover from failed migration

When running
python3 manage.py migrate
I was asked what the default value of 'id' should be and entered 1. I had read
https://docs.djangoproject.com/en/1.9/howto/writing-migrations/#migrations-that-add-unique-fields
but that was a bit too complicated for me so tried 1.
Now when I run
python3 manage.py migrate
I get the following error:
vagrant#vagrant-ubuntu-trusty-64:/vagrant/grader$ python3 manage.py migrate
Operations to perform:
Apply all migrations: admin, core, contenttypes, auth, sessions
Running migrations:
Rendering model states... DONE
Applying core.0002_auto_20160103_1302...Traceback (most recent call last):
File "/usr/local/lib/python3.4/dist-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
psycopg2.ProgrammingError: multiple default values specified for column "id" of table "core_student"
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python3.4/dist-packages/django/core/management/__init__.py", line 350, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python3.4/dist-packages/django/core/management/__init__.py", line 342, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python3.4/dist-packages/django/core/management/base.py", line 348, in run_from_argv
self.execute(*args, **cmd_options)
File "/usr/local/lib/python3.4/dist-packages/django/core/management/base.py", line 399, in execute
output = self.handle(*args, **options)
File "/usr/local/lib/python3.4/dist-packages/django/core/management/commands/migrate.py", line 200, in handle
executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial)
File "/usr/local/lib/python3.4/dist-packages/django/db/migrations/executor.py", line 92, in migrate
self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_initial)
File "/usr/local/lib/python3.4/dist-packages/django/db/migrations/executor.py", line 121, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
File "/usr/local/lib/python3.4/dist-packages/django/db/migrations/executor.py", line 198, in apply_migration
state = migration.apply(state, schema_editor)
File "/usr/local/lib/python3.4/dist-packages/django/db/migrations/migration.py", line 123, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "/usr/local/lib/python3.4/dist-packages/django/db/migrations/operations/fields.py", line 62, in database_forwards
field,
File "/usr/local/lib/python3.4/dist-packages/django/db/backends/base/schema.py", line 396, in add_field
self.execute(sql, params)
File "/usr/local/lib/python3.4/dist-packages/django/db/backends/base/schema.py", line 110, in execute
cursor.execute(sql, params)
File "/usr/local/lib/python3.4/dist-packages/django/db/backends/utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/usr/local/lib/python3.4/dist-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/usr/local/lib/python3.4/dist-packages/django/db/utils.py", line 95, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/usr/local/lib/python3.4/dist-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/usr/local/lib/python3.4/dist-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: multiple default values specified for column "id" of table "core_student"
How can I recover from this failed migration? I went into the psql command promt and typed
SELECT * FROM core_students
It returned 0 rows so I don'w know why I have a problem.
Shouldn't Django automatically make the 'id' field be unique numbers?
EDIT:
The id has been auto generated by the Django migration.
student model:
class Student(models.Model):
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
owner = models.ForeignKey('auth.User', related_name='students')
identity_number = models.CharField(max_length=50)
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
I often run into a similar problem where a migration fails for whatever reason, and only part of it gets applied to the database.
In theory you should be able to go into the database and run queries to finish the migration, but knowing what exact queries to run and what parts of the migration haven't been run is difficult in my experience.
The most dependable way I've found to fix it is to fake the migration, then back up the model, comment it out in models.py, then make a migration to delete it, then fake that as well. Then I can go into the database, drop the table, and then make a new migration to recreate it the way I now want to be.
Here are the commands I run:
python manage.py migrate --fake [appname] #fake the failed migration
#comment out the model in models.py and back up the data
python manage.py makemigrations [appname]
python manage.py migrate --fake [appname] #fake the migration to delete
the table
python manage.py dbshell
#drop the table. Mysql would be: DROP TABLE [appname]_[modelname];
#exit dbshell
#Uncomment the model in models.py adding in whatever changes were originally wanted
python manage.py makemigrations [appname]
python manage.py migrate #assuming your model change is valid, this should work this time.
#reload your data into the table
No, it's not elegant, but it gets django migrations working again without having to guess how far django got through a migration before it failed.

Django migrate model with user in a foreignkey fails

Im trying to migrate my django model:
from django.contrib.auth.models import User
class Post(models.Model):
headline = models.CharField(max_length=200)
slug = models.SlugField(max_length=200)
body = models.TextField(blank=True, null=True)
author = models.ForeignKey(User, null=True, blank=True)
I added the author field after I created the model.
Here is the migration django creates:
# encoding: utf8
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [('articles', '0002_auto')]
operations = [
migrations.AddField(
field = models.ForeignKey(to_field=u'id', to=u'auth.User', blank=True, null=True),
name = 'author',
model_name = 'post',
),
]
Here is my traceback when I try to run ./manage.py migrate:
Operations to perform:
Synchronize unmigrated apps: ckeditor, sessions, admin, messages, auth, staticfiles, contenttypes, django_extensions
Apply all migrations: articles
Synchronizing apps without migrations:
Creating tables...
Installing custom SQL...
Installing indexes...
Installed 0 object(s) from 0 fixture(s)
Running migrations:
Applying articles.0002_post_author...Traceback (most recent call last):
File "./manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/home/USER/.virtualenvs/PROJECT/src/django-trunk/django/core/management/__init__.py", line 397, in execute_from_command_line
utility.execute()
File "/home/USER/.virtualenvs/PROJECT/src/django-trunk/django/core/management/__init__.py", line 390, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/USER/.virtualenvs/PROJECT/src/django-trunk/django/core/management/base.py", line 242, in run_from_argv
self.execute(*args, **options.__dict__)
File "/home/USER/.virtualenvs/PROJECT/src/django-trunk/django/core/management/base.py", line 289, in execute
output = self.handle(*args, **options)
File "/home/USER/.virtualenvs/PROJECT/src/django-trunk/django/core/management/commands/migrate.py", line 116, in handle
executor.migrate(targets, plan, fake=options.get("fake", False))
File "/home/USER/.virtualenvs/PROJECT/src/django-trunk/django/db/migrations/executor.py", line 60, in migrate
self.apply_migration(migration, fake=fake)
File "/home/USER/.virtualenvs/PROJECT/src/django-trunk/django/db/migrations/executor.py", line 73, in apply_migration
migration.apply(project_state, schema_editor)
File "/home/USER/.virtualenvs/PROJECT/src/django-trunk/django/db/migrations/migration.py", line 80, in apply
operation.database_forwards(self.app_label, schema_editor, project_state, new_state)
File "/home/USER/.virtualenvs/PROJECT/src/django-trunk/django/db/migrations/operations/fields.py", line 22, in database_forwards
schema_editor.add_field(from_model, to_model._meta.get_field_by_name(self.name)[0])
File "/home/USER/.virtualenvs/PROJECT/src/django-trunk/django/db/backends/schema.py", line 349, in add_field
definition, params = self.column_sql(model, field, include_default=True)
File "/home/USER/.virtualenvs/PROJECT/src/django-trunk/django/db/backends/schema.py", line 105, in column_sql
db_params = field.db_parameters(connection=self.connection)
File "/home/USER/.virtualenvs/PROJECT/src/django-trunk/django/db/models/fields/related.py", line 1285, in db_parameters
return {"type": self.db_type(connection), "check": []}
File "/home/USER/.virtualenvs/PROJECT/src/django-trunk/django/db/models/fields/related.py", line 1276, in db_type
rel_field = self.related_field
File "/home/USER/.virtualenvs/PROJECT/src/django-trunk/django/db/models/fields/related.py", line 1183, in related_field
return self.foreign_related_fields[0]
File "/home/USER/.virtualenvs/PROJECT/src/django-trunk/django/db/models/fields/related.py", line 971, in foreign_related_fields
return tuple(rhs_field for lhs_field, rhs_field in self.related_fields)
File "/home/USER/.virtualenvs/PROJECT/src/django-trunk/django/db/models/fields/related.py", line 958, in related_fields
self._related_fields = self.resolve_related_fields()
File "/home/USER/.virtualenvs/PROJECT/src/django-trunk/django/db/models/fields/related.py", line 943, in resolve_related_fields
raise ValueError('Related model %r cannot been resolved' % self.rel.to)
ValueError: Related model u'auth.User' cannot been resolved
Anyone know what I'm doing wrong?
What helped me in this situation:
Delete all migration files except __init__.py (/%prjname%/migrations folder)
python manage.py makemigrations
python manage.py migrate
Not sure about exact cause, but i tried to use files, generated by my code-partner and it didn't work out.
Ok, this is another funky feature of Django which cost me hours to figure it out. According to https://docs.djangoproject.com/en/1.8/topics/auth/customizing/#substituting-a-custom-user-model:
Due to limitations of Django’s dynamic dependency feature for swappable models, you must ensure that the model referenced by AUTH_USER_MODEL is created in the first migration of its app (usually called 0001_initial); otherwise, you will have dependency issues.
So to solve this problem the best "clean" way is to put your custom user model creation in 0001_initial.py and it will simply work. And that's the real reason why Lebedev Sergey's delete/makemigrations trick can work.
If you make this change after you have applied ANY other migrations, you need to delete everything else in the migration folder and then run "python manage.py makemigrations". Then whatever you used for AUTH_USER_MODEL will be your first migration.
This probably isn't your problem if you're not using a custom user model, but remember to always use get_user_model() or when referencing the User class. Also, when defining a foreign key, settings.AUTH_USER_MODEL works, too, as in:
class MyModel(models.Model):
person = models.ForeignKey(settings.AUTH_USER_MODEL)