Can migrate with models.DateTimeField() but SQL Error with models.TimeField() - python

I have a Django model that is not working properly. When I migrate the following, I don't get any errors and I get an id, question_text, and time column in my database:
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
class Question(models.Model):
question_text = models.CharField(max_length=200)
time = models.DateTimeField()
def __str__(self):
return self.question_text
But if I change the models.DateTimeField() to models.TimeField(), I can successfuly run python3 manage.py makemigrations:
Migrations for 'app':
app/migrations/0001_initial.py
- Create model Question
But when I then try to run python3 manage.py migrate, I get the following error:
Operations to perform:
Apply all migrations: admin, app, auth, contenttypes, sessions
Running migrations:
Applying app.0002_question_time...Traceback (most recent call last):
File "/usr/local/Cellar/python/3.7.6/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "/usr/local/Cellar/python/3.7.6/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 71, in execute
return self.cursor.execute(query, args)
File "/usr/local/Cellar/python/3.7.6/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/MySQLdb/cursors.py", line 206, in execute
res = self._query(query)
File "/usr/local/Cellar/python/3.7.6/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/MySQLdb/cursors.py", line 319, in _query
db.query(q)
File "/usr/local/Cellar/python/3.7.6/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/MySQLdb/connections.py", line 259, in query
_mysql.connection.query(self, query)
MySQLdb._exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(6) DEFAULT '22:12:07.640513' NOT NULL' at line 1")
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 22, in <module>
main()
File "manage.py", line 19, in main
execute_from_command_line(sys.argv)
File "/usr/local/Cellar/python/3.7.6/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
utility.execute()
File "/usr/local/Cellar/python/3.7.6/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/Cellar/python/3.7.6/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv
self.execute(*args, **cmd_options)
File "/usr/local/Cellar/python/3.7.6/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/base.py", line 364, in execute
output = self.handle(*args, **options)
File "/usr/local/Cellar/python/3.7.6/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/base.py", line 83, in wrapped
res = handle_func(*args, **kwargs)
File "/usr/local/Cellar/python/3.7.6/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 234, in handle
fake_initial=fake_initial,
File "/usr/local/Cellar/python/3.7.6/Frameworks/Python.framework/Versions/3.7/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 "/usr/local/Cellar/python/3.7.6/Frameworks/Python.framework/Versions/3.7/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 "/usr/local/Cellar/python/3.7.6/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/migrations/executor.py", line 245, in apply_migration
state = migration.apply(state, schema_editor)
File "/usr/local/Cellar/python/3.7.6/Frameworks/Python.framework/Versions/3.7/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 "/usr/local/Cellar/python/3.7.6/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/migrations/operations/fields.py", line 112, in database_forwards
field,
File "/usr/local/Cellar/python/3.7.6/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/backends/mysql/schema.py", line 44, in add_field
super().add_field(model, field)
File "/usr/local/Cellar/python/3.7.6/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/backends/base/schema.py", line 447, in add_field
self.execute(sql, params)
File "/usr/local/Cellar/python/3.7.6/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/backends/base/schema.py", line 137, in execute
cursor.execute(sql, params)
File "/usr/local/Cellar/python/3.7.6/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/backends/utils.py", line 99, in execute
return super().execute(sql, params)
File "/usr/local/Cellar/python/3.7.6/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/backends/utils.py", line 67, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/usr/local/Cellar/python/3.7.6/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/backends/utils.py", line 76, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/usr/local/Cellar/python/3.7.6/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "/usr/local/Cellar/python/3.7.6/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/utils.py", line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/usr/local/Cellar/python/3.7.6/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "/usr/local/Cellar/python/3.7.6/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 71, in execute
return self.cursor.execute(query, args)
File "/usr/local/Cellar/python/3.7.6/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/MySQLdb/cursors.py", line 206, in execute
res = self._query(query)
File "/usr/local/Cellar/python/3.7.6/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/MySQLdb/cursors.py", line 319, in _query
db.query(q)
File "/usr/local/Cellar/python/3.7.6/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/MySQLdb/connections.py", line 259, in query
_mysql.connection.query(self, query)
django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(6) DEFAULT '22:12:07.640513' NOT NULL' at line 1")
This error happens EVEN IF I reverse all the migrations (either manually or with python3 manage.py migrate app zero), delete the migration files, and skip to step 2 (which is just starting with the models.TimeField). Does anyone know why this is? I've included my migration file for reference:
# Generated by Django 2.2.10 on 2021-06-17 22:16
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Question',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('question_text', models.CharField(max_length=200)),
('time', models.TimeField()),
],
),
]
This is the result of python3 manage.py sqlmigrate app 0001
BEGIN;
--
-- Create model User
--
CREATE TABLE `app_user` (`phone_number` varchar(200) NOT NULL PRIMARY KEY, `name` varchar(200) NOT NULL);
--
-- Create model Question
--
CREATE TABLE `app_question` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `question_name` varchar(200) NOT NULL, `question_text` varchar(200) NOT NULL, `creation_date` datetime NOT NULL, `time` time(6) NOT NULL);
CREATE TABLE `app_question_users` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `question_id` integer NOT NULL, `user_id` varchar(200) NOT NULL);
ALTER TABLE `app_question` ADD CONSTRAINT `app_question_question_text_time_d3def135_uniq` UNIQUE (`question_text`, `time`);
ALTER TABLE `app_question_users` ADD CONSTRAINT `app_question_users_question_id_9a89887c_fk_app_question_id` FOREIGN KEY (`question_id`) REFERENCES `app_question` (`id`);
ALTER TABLE `app_question_users` ADD CONSTRAINT `app_question_users_user_id_043c67c7_fk_app_user_phone_number` FOREIGN KEY (`user_id`) REFERENCES `app_user` (`phone_number`);
ALTER TABLE `app_question_users` ADD CONSTRAINT `app_question_users_question_id_user_id_04063864_uniq` UNIQUE (`question_id`, `user_id`);
COMMIT;

Try to inspect the generated SQL using the command:
python manage.py sqlmigrate <app_name> <migration_file_number>.
Sometimes, I'm running this and execute the SQL on a separate SQL client to get more information regarding the errors.

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

Unable to migrate models from django to sql server

I'm trying to learn django and have to use sql server as a data base and unable to migrate models using manage.py migrate
I'm using django 2.1.8
Pyodbc
python 3.7.3
I've tried to reinstall django, python and even sql server but it didn't solve the problem.
On running py manage.py migrate, i get the following error
py manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions, testApp
Running migrations:
Applying contenttypes.0001_initial...Traceback (most recent call last):
File "C:\Users\Hamza\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\Hamza\AppData\Local\Programs\Python\Python37-32\lib\site-packages\sql_server\pyodbc\base.py", line 546, in execute
return self.cursor.execute(sql, params)
pyodbc.ProgrammingError: ('42S02', '[42S02] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Cannot find the object "django_content_type" because it does not exist or you do not have permissions. (4902) (SQLExecDirectW)')
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "C:\Users\Hamza\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line
utility.execute()
File "C:\Users\Hamza\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\Hamza\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\base.py", line 316, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\Hamza\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\base.py", line 353, in execute
output = self.handle(*args, **options)
File "C:\Users\Hamza\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\base.py", line 83, in wrapped
res = handle_func(*args, **kwargs)
File "C:\Users\Hamza\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\commands\migrate.py", line 203, in handle
fake_initial=fake_initial,
File "C:\Users\Hamza\AppData\Local\Programs\Python\Python37-32\lib\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 "C:\Users\Hamza\AppData\Local\Programs\Python\Python37-32\lib\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 "C:\Users\Hamza\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\migrations\executor.py", line 244, in apply_migration
state = migration.apply(state, schema_editor)
File "C:\Users\Hamza\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\migrations\migration.py", line 124, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "C:\Users\Hamza\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\migrations\operations\models.py", line 514, in database_forwards
getattr(new_model._meta, self.option_name, set()),
File "C:\Users\Hamza\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\base\schema.py", line 360, in alter_unique_together
self.execute(self._create_unique_sql(model, columns))
File "C:\Users\Hamza\AppData\Local\Programs\Python\Python37-32\lib\site-packages\sql_server\pyodbc\schema.py", line 653, in execute
cursor.execute(sql, params)
File "C:\Users\Hamza\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\utils.py", line 100, in execute
return super().execute(sql, params)
File "C:\Users\Hamza\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\utils.py", line 68, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "C:\Users\Hamza\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\utils.py", line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\Users\Hamza\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\Hamza\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\utils.py", line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Users\Hamza\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\Hamza\AppData\Local\Programs\Python\Python37-32\lib\site-packages\sql_server\pyodbc\base.py", line 546, in execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: ('42S02', '[42S02] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Cannot find the object "django_content_type" because it does not exist or you do not have permissions. (4902) (SQLExecDirectW)')
I expect it to migrate but it gives me this error.
Might be a different problem, but I was having the same error. In my case I had run python manage.py migrate --fake (per other SO threads) to fix an error I had earlier and django made a record of the migration without actually creating the table. When I ran it again it assumed I was modifying a table that wasn't there.
I eventually solved this by:
Manually creating the table in SQL server with all of the correct fields
Commenting out the model code from everywhere in the models.py
python manage.py makemigrations to remove the fake table from registry
python manage.py migrate to delete the manual table I just made and update the migrations registry
then re-add the table to my models.py
then re-run python manage.py makemigrations
python manage.py migrate to sync django with SQL server

Django- Change Username field to BigAutoField?

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

Trying to migrate in Django 1.9 -- strange SQL error "django.db.utils.OperationalError: near ")": syntax error"

I don't have a clue what's causing this error. It appears to be a bug that there isn't a fix for. Could anyone tell give me a hint as to how I might get around this? It's frustrating me to no end. Thanks.
Operations to perform:
Apply all migrations: admin, contenttypes, optilab, auth, sessions
Running migrations:
Rendering model states... DONE
Applying optilab.0006_auto_20160621_1640...Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 353, in execute_from_command_line
utility.execute()
File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 345, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Python27\lib\site-packages\django\core\management\base.py", line 348, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Python27\lib\site-packages\django\core\management\base.py", line 399, in execute
output = self.handle(*args, **options)
File "C:\Python27\lib\site-packages\django\core\management\commands\migrate.py", line 200, in handle
executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial)
File "C:\Python27\lib\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 "C:\Python27\lib\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 "C:\Python27\lib\site-packages\django\db\migrations\executor.py", line 198, in apply_migration
state = migration.apply(state, schema_editor)
File "C:\Python27\lib\site-packages\django\db\migrations\migration.py", line 123, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "C:\Python27\lib\site-packages\django\db\migrations\operations\fields.py", line 121, in database_forwards
schema_editor.remove_field(from_model, from_model._meta.get_field(self.name))
File "C:\Python27\lib\site-packages\django\db\backends\sqlite3\schema.py", line 247, in remove_field
self._remake_table(model, delete_fields=[field])
File "C:\Python27\lib\site-packages\django\db\backends\sqlite3\schema.py", line 197, in _remake_table
self.quote_name(model._meta.db_table),
File "C:\Python27\lib\site-packages\django\db\backends\base\schema.py", line 110, in execute
cursor.execute(sql, params)
File "C:\Python27\lib\site-packages\django\db\backends\utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "C:\Python27\lib\site-packages\django\db\backends\utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "C:\Python27\lib\site-packages\django\db\utils.py", line 95, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "C:\Python27\lib\site-packages\django\db\backends\utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "C:\Python27\lib\site-packages\django\db\backends\sqlite3\base.py", line 323, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: near ")": syntax error
Here's the contents of 0006_auto_20160621_1640.py
# -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-06-21 22:40
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('optilab', '0005_test'),
]
operations = [
migrations.RemoveField(
model_name='lasersubstrate',
name='substrate_ptr',
),
migrations.RemoveField(
model_name='waveguidesubstrate',
name='substrate_ptr',
),
migrations.DeleteModel(
name='LaserSubstrate',
),
migrations.DeleteModel(
name='WaveguideSubstrate',
),
]
Here's the SQL produced from running 'python manage.py sqlmigrate optilab 0006'
BEGIN;
--
-- Remove field substrate_ptr from lasersubstrate
--
ALTER TABLE "optilab_lasersubstrate" RENAME TO "optilab_lasersubstrate__old";
CREATE TABLE "optilab_lasersubstrate" ("substrate_ptr_id" integer NOT NULL PRIMARY KEY REFERENCES "optilab_substrate" ("id"));
INSERT INTO "optilab_lasersubstrate" () SELECT FROM "optilab_lasersubstrate__old";
DROP TABLE "optilab_lasersubstrate__old";
--
-- Remove field substrate_ptr from waveguidesubstrate
--
ALTER TABLE "optilab_waveguidesubstrate" RENAME TO "optilab_waveguidesubstrate__old";
CREATE TABLE "optilab_waveguidesubstrate" ("substrate_ptr_id" integer NOT NULL PRIMARY KEY REFERENCES "optilab_substrate" ("id"));
INSERT INTO "optilab_waveguidesubstrate" () SELECT FROM "optilab_waveguidesubstrate__old";
DROP TABLE "optilab_waveguidesubstrate__old";
--
-- Delete model LaserSubstrate
--
DROP TABLE "optilab_lasersubstrate";
--
-- Delete model WaveguideSubstrate
--
DROP TABLE "optilab_waveguidesubstrate";
COMMIT;
This appears to be the line that's causing the errror:
INSERT INTO "optilab_lasersubstrate" () SELECT FROM "optilab_lasersubstrate__old";
You are usually expected to have a list of columns in those parenthesis. Eg INSERT INTO "optilab_lasersubstrate" (col1,col2,etc) however the migration has produced a blank set! Similarly the SELECT FROM portion should read as SELECT col1,col2 FROM. By some strange set of events you appear to have managed to create a table with no columns!!
I see from your migration file that you are anyway dropping this table. So there isn't any reason to struggle with the RemoveField portion. It's code associated with the RemoveField that's causing the error. Change your migration as follows:
class Migration(migrations.Migration):
dependencies = [
('optilab', '0005_test'),
]
operations = [
migrations.DeleteModel(
name='LaserSubstrate',
),
migrations.DeleteModel(
name='WaveguideSubstrate',
),
]
Edit base.py in the lines that breaks and update it to:
def execute(self, query, params=None):
if params is None:
if '()' not in str(query):
return Database.Cursor.execute(self, query)
query = self.convert_query(query)
if '()' not in str(query):
return Database.Cursor.execute(self, query, params)

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