Django- Change Username field to BigAutoField? - python

I'm designing an Application where username will be an AutoIntegerField and unique.
Here's my model.
class ModelA(models.Model):
username = models.BigAutoField(primary_key=True, db_index=False)
user_id = models.UUIDField(default=uuid.uuid4, unique=True,
editable=False)
Initially, I wanted user_id to be a primary_key, but I can't create an AutoField which is not primary_key. As a result, I'd to let go off user_id as primary_key and assigned username as the primary key.
Now, when I run the migrations, it throws an error saying,
django.db.utils.ProgrammingError: operator class "varchar_pattern_ops" does not accept data type bigint
Complete StackTrace:-
Applying users.0005_auto_20180626_0914...Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
psycopg2.ProgrammingError: operator class "varchar_pattern_ops" does not accept data type bigint
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line
utility.execute()
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/management/__init__.py", line 356, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/management/base.py", line 283, in run_from_argv
self.execute(*args, **cmd_options)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/management/base.py", line 330, in execute
output = self.handle(*args, **options)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/management/commands/migrate.py", line 204, in handle
fake_initial=fake_initial,
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/migrations/executor.py", line 115, in migrate
state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/migrations/executor.py", line 244, in apply_migration
state = migration.apply(state, schema_editor)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/migrations/migration.py", line 129, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/migrations/operations/fields.py", line 216, in database_forwards
schema_editor.alter_field(from_model, from_field, to_field)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/backends/base/schema.py", line 515, in alter_field
old_db_params, new_db_params, strict)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/backends/postgresql/schema.py", line 112, in _alter_field
new_db_params, strict,
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/backends/base/schema.py", line 684, in _alter_field
params,
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/backends/base/schema.py", line 120, in execute
cursor.execute(sql, params)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/backends/utils.py", line 80, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: operator class "varchar_pattern_ops" does not accept data type bigint

I think the issue is that you still have an old index on your username field that clashes with the new type. The db_index=False argument has no effect because primary_key=True always generates an index.
You might be able to solve this by removing primary_key=True, creating a migration, and then re-adding it and creating another migration. Alternatively, you can do it by hand by dropping and re-creating the index. If you want to go down that path, consult this answer.
If your project is still in an early stage and you don't have any valuable data, you can take the easy way out and drop any tables related to your users app or even the complete database, delete all migrations in the users app and create them from scratch.

in my case I was connecting django to postgres at localhost pgadmin
first deleted all the migrations except default one and also in the pycache
then just run python manage.py makemigrations and python manage.py migrate in your terminal

Related

Django Misapplying Migrations

I am not sure whether I am doing something wrong or it is a problem with one of the pieces I am using for the project.
Basically, I added a field to a model and am trying to make a migration.
Here is the model. The field is the poster one.
class Video(models.Model):
title=models.CharField(max_length=500)
description=models.TextField(default="")
creation_date=models.DateTimeField(default=timezone.now)
videofile=models.FileField(upload_to='videos/', null=True, verbose_name="")
poster=models.ImageField(upload_to='video/thumbnails', null=True, verbose_name="")
tags = TaggableManager()
actions = ['delete']
def __str__(self):
return self.title + ": " + str(self.videofile)
...
That is the only thing that changed in the model. Let's make the migrations.
(app-web) selfishman#user-desktop:~/sites/app-web/app$ python manage.py makemigrations
Migrations for 'video_uploader':
video_uploader/migrations/0007_video_poster.py
- Add field poster to video
So far, so good. Let's try to apply the migration.
(app-web) user#user-desktop:~/sites/app-web/app$ python manage.py migrate video_uploader
Operations to perform:
Apply all migrations: video_uploader
Running migrations:
Applying video_uploader.0002_video_creation_date...Traceback (most recent call last):
File "/home/user/miniconda3/envs/app-web/lib/python3.7/site-packages/django/db/backends/ut
ils.py", line 85, in _execute
return self.cursor.execute(sql, params)
psycopg2.errors.DuplicateColumn: column "creation_date" of relation "video_uploader_video" already exists
There rest of the backtrace:
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 20, in <module>
execute_from_command_line(sys.argv)
File "/home/user/miniconda3/envs/app-web/lib/python3.7/site-packages/django/core/managemen
t/__init__.py", line 381, in execute_from_command_line
utility.execute()
File "/home/user/miniconda3/envs/app-web/lib/python3.7/site-packages/django/core/managemen
t/__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/user/miniconda3/envs/app-web/lib/python3.7/site-packages/django/core/managemen
t/base.py", line 316, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/user/miniconda3/envs/app-web/lib/python3.7/site-packages/django/core/managemen
t/base.py", line 353, in execute
output = self.handle(*args, **options)
File "/home/user/miniconda3/envs/app-web/lib/python3.7/site-packages/django/core/managemen
t/base.py", line 83, in wrapped
res = handle_func(*args, **kwargs)
File "/home/user/miniconda3/envs/app-web/lib/python3.7/site-packages/django/core/managemen
t/commands/migrate.py", line 203, in handle
fake_initial=fake_initial,
File "/home/user/miniconda3/envs/app-web/lib/python3.7/site-packages/django/db/migrations/
executor.py", line 117, in migrate
state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
File "/home/user/miniconda3/envs/app-web/lib/python3.7/site-packages/django/db/migrations/
executor.py", line 147, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
File "/home/user/miniconda3/envs/app-web/lib/python3.7/site-packages/django/db/migrations/
executor.py", line 244, in apply_migration
state = migration.apply(state, schema_editor)
File "/home/user/miniconda3/envs/app-web/lib/python3.7/site-packages/django/db/migrations/
migration.py", line 124, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "/home/user/miniconda3/envs/app-web/lib/python3.7/site-packages/django/db/migrations/
operations/fields.py", line 84, in database_forwards
field,
File "/home/user/miniconda3/envs/app-web/lib/python3.7/site-packages/django/db/backends/ba
se/schema.py", line 435, in add_field
self.execute(sql, params)
File "/home/user/miniconda3/envs/app-web/lib/python3.7/site-packages/django/db/backends/ba
se/schema.py", line 133, in execute
cursor.execute(sql, params)
File "/home/user/miniconda3/envs/app-web/lib/python3.7/site-packages/django/db/backends/ut
ils.py", line 100, in execute
return super().execute(sql, params)
File "/home/user/miniconda3/envs/app-web/lib/python3.7/site-packages/django/db/backends/ut
ils.py", line 68, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/home/user/miniconda3/envs/app-web/lib/python3.7/site-packages/django/db/backends/ut
ils.py", line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/home/user/miniconda3/envs/app-web/lib/python3.7/site-packages/django/db/backends/ut
ils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "/home/user/miniconda3/envs/app-web/lib/python3.7/site-packages/django/db/utils.py",
line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/home/user/miniconda3/envs/app-web/lib/python3.7/site-packages/django/db/backends/ut
ils.py", line 85, in _execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: column "creation_date" of relation "video_uploader_video" already exists
This is the migration that was created:
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('video_uploader', '0006_video_description'),
]
operations = [
migrations.AddField(
model_name='video',
name='poster',
field=models.ImageField(null=True, upload_to='video/thumbnails', verbose_name=''),
),
]
Could someone tell me what is going on here? I am using Postgres 12. When I run tests, and an (SQLite) DB is created from scratch, there is no such error.
Any help is appreciated.
P.S. We have seen quite a few inconsistencies when it comes to Django migrations and Postgres/Psycopg2. Not sure if something is up with the config or versions/dependencies.
You created a new migration and it was named
0007_video_poster
However when you run the migrate it is running
0002_video_creation_date
And this is trying to create a new column named creation_date however that's already there.
You are getting inconsistent results because django thinks the previous migrations were not applied and therefore it is trying to apply them.
The easiest way would be to flush the database (make sure you first export any data you might need) using
python manage.py flush
This would reset the database and then you can run the migrations normally and it should work fine.
Otherwise if you want to execute the migration you just created i.e. 0007_video_poster
You can run this
python manage.py migrate video_uploader 0007_video_poster

Django unable to migrate PostgreSQL: constraint X of relation Y does not exist

I'm trying to run a Django 1.11 migration on a PostgreSQL 9.6.5 database, and I'm getting the odd error:
Applying myapp.0011_auto_20171130_1807...Traceback (most recent call last):
File "manage.py", line 9, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line
utility.execute()
File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 356, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv
self.execute(*args, **cmd_options)
File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/core/management/base.py", line 330, in execute
output = self.handle(*args, **options)
File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 204, in handle
fake_initial=fake_initial,
File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 115, in migrate
state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 244, in apply_migration
state = migration.apply(state, schema_editor)
File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/db/migrations/migration.py", line 129, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/db/migrations/operations/models.py", line 536, in database_forwards
getattr(new_model._meta, self.option_name, set()),
File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/db/backends/base/schema.py", line 349, in alter_unique_together
self._delete_composed_index(model, fields, {'unique': True}, self.sql_delete_unique)
File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/db/backends/base/schema.py", line 380, in _delete_composed_index
self.execute(self._delete_constraint_sql(sql, model, constraint_names[0]))
File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/db/backends/base/schema.py", line 120, in execute
cursor.execute(sql, params)
File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/db/utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: constraint "idx_32269_myapp_mymodel_title_333195ae82ac2107_uniq" of relation "myapp_mymodel" does not exist
The migration is changing a unique contract from including one column to two. Pretty simple. It needs to destroy the old index, "idx_32269_myapp_mymodel_title_333195ae82ac2107_uniq", before creating the new one. However, it fails because it doesn't think the old one exists.
So I connected to the database with pgAdminIII and inspected the table, and contrary to the error message, the table does have an index called idx_32269_myapp_mymodel_title_333195ae82ac2107_uniq.
I thought maybe Django is using slightly different connection parameters, and is connecting to a different database? Let's try inspecting it from inside a Django dbshell. So I started manage.py dbshell and ran:
SELECT *
FROM pg_stat_all_indexes
WHERE indexrelname='idx_32269_myapp_mymodel_title_333195ae82ac2107_uniq';
and it returned one row.
Why is Django unable to see this index during a migration, even though the index definitely exists in the database?
The problem turned out to be that I converted the database to PostgreSQL from MySQL using the tool pgloader, and this tool converts constraints by creating them as indexes in PostgreSQL, whereas the Django PG backend creates them as constraints. So when the migration runs, it only looks for constraints and doesn't find any.
I fixed this by dropping the index and re-creating it as a true constraint with:
DROP INDEX idx_32269_myapp_mymodel_title_333195ae82ac2107_uniq;
ALTER TABLE public.myapp_mymodel ADD CONSTRAINT idx_32269_myapp_mymodel_title_333195ae82ac2107_uniq UNIQUE(title);
After that, the Django migration ran correctly.

Django: duplicate key value violates unique constraint

I have a Joke model:
class Joke(models.Model):
...
date_created = models.DateTimeField(default=datetime.now, blank=True)
date_modified = models.DateTimeField(default=datetime.now, blank=True)
creator = models.OneToOneField(User, default=1)
Now, when I try to migrate the last line I get errors. Basically, I want to link a User to the Joke object, and since I already have a database, I want the default value to be 1, which is the admin user's id(I checked...). Makemigrations works just fine but when I try to migrate, I get this:
Operations to perform:
Apply all migrations: jokes_app, sessions, contenttypes, auth, taggit, default, admin
Running migrations:
Rendering model states... DONE
Applying jokes_app.0008_auto_20160723_1559...Traceback (most recent call last):
File "/home/antoni4040/Documents/Jokes_Website/django-jokes/venv/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
psycopg2.IntegrityError: duplicate key value violates unique constraint "jokes_app_joke_creator_id_key"
DETAIL: Key (creator_id)=(1) already exists.
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/antoni4040/Documents/Jokes_Website/django-jokes/venv/lib/python3.4/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line
utility.execute()
File "/home/antoni4040/Documents/Jokes_Website/django-jokes/venv/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/antoni4040/Documents/Jokes_Website/django-jokes/venv/lib/python3.4/site-packages/django/core/management/base.py", line 348, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/antoni4040/Documents/Jokes_Website/django-jokes/venv/lib/python3.4/site-packages/django/core/management/base.py", line 399, in execute
output = self.handle(*args, **options)
File "/home/antoni4040/Documents/Jokes_Website/django-jokes/venv/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/antoni4040/Documents/Jokes_Website/django-jokes/venv/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/antoni4040/Documents/Jokes_Website/django-jokes/venv/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/antoni4040/Documents/Jokes_Website/django-jokes/venv/lib/python3.4/site-packages/django/db/migrations/executor.py", line 198, in apply_migration
state = migration.apply(state, schema_editor)
File "/home/antoni4040/Documents/Jokes_Website/django-jokes/venv/lib/python3.4/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/antoni4040/Documents/Jokes_Website/django-jokes/venv/lib/python3.4/site-packages/django/db/migrations/operations/fields.py", line 201, in database_forwards
schema_editor.alter_field(from_model, from_field, to_field)
File "/home/antoni4040/Documents/Jokes_Website/django-jokes/venv/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 482, in alter_field
old_db_params, new_db_params, strict)
File "/home/antoni4040/Documents/Jokes_Website/django-jokes/venv/lib/python3.4/site-packages/django/db/backends/postgresql/schema.py", line 110, in _alter_field
new_db_params, strict,
File "/home/antoni4040/Documents/Jokes_Website/django-jokes/venv/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 644, in _alter_field
[new_default],
File "/home/antoni4040/Documents/Jokes_Website/django-jokes/venv/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 110, in execute
cursor.execute(sql, params)
File "/home/antoni4040/Documents/Jokes_Website/django-jokes/venv/lib/python3.4/site-packages/django/db/backends/utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/home/antoni4040/Documents/Jokes_Website/django-jokes/venv/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/home/antoni4040/Documents/Jokes_Website/django-jokes/venv/lib/python3.4/site-packages/django/db/utils.py", line 95, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/home/antoni4040/Documents/Jokes_Website/django-jokes/venv/lib/python3.4/site-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/home/antoni4040/Documents/Jokes_Website/django-jokes/venv/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
django.db.utils.IntegrityError: duplicate key value violates unique constraint "jokes_app_joke_creator_id_key"
DETAIL: Key (creator_id)=(1) already exists.
I really don't understand what's wrong. Any ideas?
OneToOne field enforces, as it's name says, an one-to-one relationship, which in your case means that one user can be creator of one and only one joke - definitely not what you want. Use ForeignKey instead:
creator = models.ForeignKey(User, default=1, on_delete=models.SET_DEFAULT)

django changing a date field to integer field can't migrate

I recently changed a date field to an integer field (the data was specified in number of months remaining rather than a date).
However all though the make migrations command works fine when I attempt to migrate this fails with a typecast error (note using postgres 9.5). Note there was only 1 instance/entry of the model, which I have also now deleted and the migrate still fails for some reason?
File "/Users/Yunti/.virtualenvs/switcher5/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
psycopg2.ProgrammingError: cannot cast type date to integer
LINE 1: ...end_date_fixed" TYPE integer USING "end_date_fixed"::integer
^
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 "/Users/Yunti/.virtualenvs/switcher5/lib/python3.5/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line
utility.execute()
File "/Users/Yunti/.virtualenvs/switcher5/lib/python3.5/site-packages/django/core/management/__init__.py", line 345, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/Yunti/.virtualenvs/switcher5/lib/python3.5/site-packages/django/core/management/base.py", line 348, in run_from_argv
self.execute(*args, **cmd_options)
File "/Users/Yunti/.virtualenvs/switcher5/lib/python3.5/site-packages/django/core/management/base.py", line 399, in execute
output = self.handle(*args, **options)
File "/Users/Yunti/.virtualenvs/switcher5/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 "/Users/Yunti/.virtualenvs/switcher5/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 "/Users/Yunti/.virtualenvs/switcher5/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 "/Users/Yunti/.virtualenvs/switcher5/lib/python3.5/site-packages/django/db/migrations/executor.py", line 198, in apply_migration
state = migration.apply(state, schema_editor)
File "/Users/Yunti/.virtualenvs/switcher5/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 "/Users/Yunti/.virtualenvs/switcher5/lib/python3.5/site-packages/django/db/migrations/operations/fields.py", line 201, in database_forwards
schema_editor.alter_field(from_model, from_field, to_field)
File "/Users/Yunti/.virtualenvs/switcher5/lib/python3.5/site-packages/django/db/backends/base/schema.py", line 482, in alter_field
old_db_params, new_db_params, strict)
File "/Users/Yunti/.virtualenvs/switcher5/lib/python3.5/site-packages/django/db/backends/postgresql/schema.py", line 110, in _alter_field
new_db_params, strict,
File "/Users/Yunti/.virtualenvs/switcher5/lib/python3.5/site-packages/django/db/backends/base/schema.py", line 634, in _alter_field
params,
File "/Users/Yunti/.virtualenvs/switcher5/lib/python3.5/site-packages/django/db/backends/base/schema.py", line 110, in execute
cursor.execute(sql, params)
File "/Users/Yunti/.virtualenvs/switcher5/lib/python3.5/site-packages/django/db/backends/utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/Users/Yunti/.virtualenvs/switcher5/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/Users/Yunti/.virtualenvs/switcher5/lib/python3.5/site-packages/django/db/utils.py", line 95, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/Users/Yunti/.virtualenvs/switcher5/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/Users/Yunti/.virtualenvs/switcher5/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: cannot cast type date to integer
LINE 1: ...end_date_fixed" TYPE integer USING "end_date_fixed"::integer
If the table is empty.
Do the migration in two simple steps. Step 1, drop the existing date column from the model. Step 2 add a new INTEGER column with the same column name.
If the table is not empty.
Edit your model to change the type of end_date_fixed to integer as you have done. Do the make migrations, the open the migrations and delete everything inside migrations[] then replacce it with
migrations.RunSQL("ALTER TABLE mytable ALTER end_date_fixed TYPE INTEGER USING EXTRACT(epoch FROM end_date_fixed)
Make sure that you have not made any other changes to the model when you try this method.

Django Migration: NOT NULL constraint failed

here its my model code
class student(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
available = models.BooleanField(default=False, blank=True)
In above model available is my new field, now I want to migrate database but it give me error, when I'm run following command
python manage.py migrate
Operations to perform:
Apply all migrations: student
Running migrations:
Applying order.0004_auto_20150223_1758...Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/home/nikhil/live-devEnv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
utility.execute()
File "/home/nikhil/live-devEnv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 377, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/nikhil/live-devEnv/local/lib/python2.7/site-packages/django/core/management/base.py", line 288, in run_from_argv
self.execute(*args, **options.__dict__)
File "/home/nikhil/live-devEnv/local/lib/python2.7/site-packages/django/core/management/base.py", line 338, in execute
output = self.handle(*args, **options)
File "/home/nikhil/live-devEnv/local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 160, in handle
executor.migrate(targets, plan, fake=options.get("fake", False))
File "/home/nikhil/live-devEnv/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 63, in migrate
self.apply_migration(migration, fake=fake)
File "/home/nikhil/live-devEnv/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 97, in apply_migration
migration.apply(project_state, schema_editor)
File "/home/nikhil/live-devEnv/local/lib/python2.7/site-packages/django/db/migrations/migration.py", line 107, in apply
operation.database_forwards(self.app_label, schema_editor, project_state, new_state)
File "/home/nikhil/live-devEnv/local/lib/python2.7/site-packages/django/db/migrations/operations/fields.py", line 37, in database_forwards
field,
File "/home/nikhil/live-devEnv/local/lib/python2.7/site-packages/django/db/backends/sqlite3/schema.py", line 167, in add_field
self._remake_table(model, create_fields=[field])
File "/home/nikhil/live-devEnv/local/lib/python2.7/site-packages/django/db/backends/sqlite3/schema.py", line 135, in _remake_table
self.quote_name(model._meta.db_table),
File "/home/nikhil/live-devEnv/local/lib/python2.7/site-packages/django/db/backends/schema.py", line 99, in execute
cursor.execute(sql, params)
File "/home/nikhil/live-devEnv/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 81, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/home/nikhil/live-devEnv/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "/home/nikhil/live-devEnv/local/lib/python2.7/site-packages/django/db/utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/home/nikhil/live-devEnv/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "/home/nikhil/live-devEnv/local/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py", line 485, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: NOT NULL constraint failed: student.available
something wrong here please give me a solution for above problem.
I had this issue, when I wanted to change a field to be non-nullable, but there were already data in the database, where this value was null, which brought the conflict. I was able to resolve it by
Add the nullable field.
migrations.AddField(
model_name='mymodel',
name='new_field',
field=models.OneToOneField(to='app.OtherModel', null=True, default=None),
preserve_default=False,
),
Use RunPython to populate the fields of the existing data with something that made sense
migrations.RunPython(fix_null_fields)
Finally alter the field to be non-nullable
migrations.AlterField(
model_name='mymodel',
name='new_field',
field=models.OneToOneField(to='app.OtherModel'),
preserve_default=True,
),
This seemed to work for me without any trouble. For more information, look into Migrations and Migration operations

Categories