There is this error showing after I have used makemigrations command
I have tried commenting different column for it but it wont work
C:\Users\Rushabh\Desktop\project\MyPrj>python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, paper, sessions
Running migrations:
Applying paper.0014_auto_20170405_1549...Traceback (most recent call last):
File "C:\Users\Rushabh\Anaconda3\lib\site-packages\django\db\backends\utils.py", line 62, in execute
return self.cursor.execute(sql)
File "C:\Users\Rushabh\Anaconda3\lib\site-packages\django\db\backends\sqlite3\base.py", line 335, in execute
return Database.Cursor.execute(self, query)
sqlite3.OperationalError: near "[]": syntax error
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 "C:\Users\Rushabh\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_command_line
utility.execute()
File "C:\Users\Rushabh\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 359, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\Rushabh\Anaconda3\lib\site-packages\django\core\management\base.py", line 294, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\Rushabh\Anaconda3\lib\site-packages\django\core\management\base.py", line 345, in execute
output = self.handle(*args, **options)
File "C:\Users\Rushabh\Anaconda3\lib\site-packages\django\core\management\commands\migrate.py", line 204, in handle
fake_initial=fake_initial,
File "C:\Users\Rushabh\Anaconda3\lib\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 "C:\Users\Rushabh\Anaconda3\lib\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 "C:\Users\Rushabh\Anaconda3\lib\site-packages\django\db\migrations\executor.py", line 244, in apply_migration
state = migration.apply(state, schema_editor)
File "C:\Users\Rushabh\Anaconda3\lib\site-packages\django\db\migrations\migration.py", line 129, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "C:\Users\Rushabh\Anaconda3\lib\site-packages\django\db\migrations\operations\fields.py", line 84, in database_forwards
field,
File "C:\Users\Rushabh\Anaconda3\lib\site-packages\django\db\backends\sqlite3\schema.py", line 231, in add_field
self._remake_table(model, create_fields=[field])
File "C:\Users\Rushabh\Anaconda3\lib\site-packages\django\db\backends\sqlite3\schema.py", line 191, in _remake_table
self.create_model(temp_model)
File "C:\Users\Rushabh\Anaconda3\lib\site-packages\django\db\backends\base\schema.py", line 295, in create_model
self.execute(sql, params or None)
File "C:\Users\Rushabh\Anaconda3\lib\site-packages\django\db\backends\base\schema.py", line 112, in execute
cursor.execute(sql, params)
File "C:\Users\Rushabh\Anaconda3\lib\site-packages\django\db\backends\utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "C:\Users\Rushabh\Anaconda3\lib\site-packages\django\db\backends\utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "C:\Users\Rushabh\Anaconda3\lib\site-packages\django\db\utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "C:\Users\Rushabh\Anaconda3\lib\site-packages\django\utils\six.py", line 685, in reraise
raise value.with_traceback(tb)
File "C:\Users\Rushabh\Anaconda3\lib\site-packages\django\db\backends\utils.py", line 62, in execute
return self.cursor.execute(sql)
File "C:\Users\Rushabh\Anaconda3\lib\site-packages\django\db\backends\sqlite3\base.py", line 335, in execute
return Database.Cursor.execute(self, query)
django.db.utils.OperationalError: near "[]": syntax error
Migration file
from __future__ import unicode_literals
import django.contrib.postgres.fields
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('paper', '0019_auto_20170405_1659'),
]
operations = [
migrations.AddField(
model_name='test',
name='checked',
field=models.BooleanField(default=False),
),
migrations.AddField(
model_name='test',
name='mark3',
field=django.contrib.postgres.fields.ArrayField(base_field=models.CharField(max_length=5), default=[], size=None),
),
migrations.AddField(
model_name='test',
name='mark4',
field=django.contrib.postgres.fields.ArrayField(base_field=models.CharField(max_length=5), default=[], size=None),
),
migrations.AddField(
model_name='test',
name='mark7',
field=django.contrib.postgres.fields.ArrayField(base_field=models.CharField(max_length=5), default=[], size=None),
),
migrations.AddField(
model_name='test',
name='request',
field=models.BooleanField(default=False),
),
]
The problem arose after I added the following field to my models
mark3=ArrayField(models.CharField(max_length=5),default=[])
The models.py file is
from django.db import models
from django.contrib.postgres.fields import ArrayField
class User(models.Model):
user_id=models.CharField(unique=True,max_length=50)
password=models.CharField(max_length=50)
role=models.IntegerField(blank=False)
def __str__(self):
return self.user_id
class Qbank(models.Model):
user=models.ForeignKey(User,on_delete=models.CASCADE)
qbank_id=models.CharField(unique=True,max_length=50,blank=False)
# subject_id=models.CharField(max_length=50)
qbank_file=models.FileField(upload_to= 'qbs/',blank=False)
ans_file=models.FileField(upload_to= 'ans/',blank=False)
uploaded_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.qbank_id
class Test(models.Model):
qbank=models.ForeignKey(Qbank,on_delete=models.CASCADE)
test_id=models.CharField(unique=True,max_length=50)
request=models.BooleanField(default=False)
checked=models.BooleanField(default=False)
mark3=ArrayField(models.CharField(max_length=5),default=[])
mark4=ArrayField(models.CharField(max_length=5),default=[])
mark7=ArrayField(models.CharField(max_length=5),default=[])
# true if send and checked respt
def __str__(self):
return self.test_id
I puzzled over this one for a little while too. The ArrayField is specific to Postgres, and is imported from a Postgres library:
import django.contrib.postgres.fields
It looks like you're trying to commit your migrations to SQLite. You should set up a local Postgres database, and update your settings.py file from:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
To:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'DATABASE NAME',
'USER': 'USER NAME',
'PASSWORD': 'USER PASSWORD',
'HOST': 'localhost',
'PORT': '5432',
}
}
Also, you are incorrectly setting the default value for your ArrayField. Per Django ArrayField documentation, you should not use [] as the default. It won't cause this problem, but it will probably create some others! You should use default=list instead of default=[], which will create a mutable default shared between all instances of ArrayField:
Instead of:
mark7=ArrayField(models.CharField(max_length=5),default=[])
Try:
mark7=ArrayField(models.CharField(max_length=5),default=list)
I stupidly used this specific posgresql field - ArrayField for the model and let the test run with sqlite. That caused the error when I pushed code to github with the travis-ci.
The ArrayField docs warn that you shouldn't use a mutable value like []. You can use the callable list for an empty default.
class Test(models.Model):
...
mark3=ArrayField(models.CharField(max_length=5), default=list)
mark4=ArrayField(models.CharField(max_length=5), default=list)
mark7=ArrayField(models.CharField(max_length=5), default=list)
After making this change, delete the old migration file and run makemigrations again.
Related
I have a postgresql database and I am making a migration to switch my pk from username to uuid.
I already made a data migration file where I add a uuid to every row in my model
it worked fine on sqlite but when I was testing it on postgresql I got an error.
The error was "django.db.utils.ProgrammingError: column "username" is in a primary key"
I am not sure where to begin to debug this thing. Here is the model, data migration, migration, and stack trace of the error:
# models.py
class UserInformation(models.Model):
uuid = models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True)
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=False)
username = models.CharField(max_length=100, unique=True, blank=True, null=True)
# data migration 42
import uuid
from django.db import migrations
def set_uuid_for_all_user_information(apps, schema_editor):
UserInformation = apps.get_model('accounts', 'UserInformation')
for userInformation_user in UserInformation.objects.all():
userInformation_user.uuid = uuid.uuid4().hex
userInformation_user.save()
class Migration(migrations.Migration):
dependencies = [
('accounts', '0041_auto_20211227_2113'),
]
operations = [
migrations.RunPython(set_uuid_for_all_user_information),
]
# migration 43 (this is where the postgresqsl error occurs) trying to change pk from username to uuid
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('accounts', '0042_auto_20211229_2319'),
]
operations = [
migrations.AlterField(
model_name='userinformation',
name='user',
field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='auth.user'),
),
migrations.AlterField(
model_name='userinformation',
name='username',
field=models.CharField(blank=True, max_length=100, null=True, unique=True),
),
migrations.AlterField(
model_name='userinformation',
name='uuid',
field=models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False),
),
]
when running python manage.py migrate, I get this error:
Tracking file by folder pattern: migrations
Operations to perform:
Apply all migrations: account, accounts, admin, auth, contenttypes, legal, sessions, sites, socialaccount
Running migrations:
Applying accounts.0043_auto_20211229_2321...Traceback (most recent call last):
File "C:\..\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
psycopg2.errors.InvalidTableDefinition: column "username" is in a primary key
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\..\python\helpers\pycharm\django_manage.py", line 52, in <module>
run_command()
File "C:\..\python\helpers\pycharm\django_manage.py", line 46, in run_command
run_module(manage_file, None, '__main__', True)
File "C:\..\Python\Python38\lib\runpy.py", line 207, in run_module
return _run_module_code(code, init_globals, run_name, mod_spec)
File "C:\..\Python\Python38\lib\runpy.py", line 97, in _run_module_code
_run_code(code, mod_globals, init_globals,
File "C:\..\Python\Python38\lib\runpy.py", line 87, in _run_code
exec(code, run_globals)
File "C:\..\my_site\manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "C:\..\venv\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line
utility.execute()
File "C:\..\venv\lib\site-packages\django\core\management\__init__.py", line 413, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\..\venv\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\..\venv\lib\site-packages\django\core\management\base.py", line 398, in execute
output = self.handle(*args, **options)
File "C:\..\venv\lib\site-packages\django\core\management\base.py", line 89, in wrapped
res = handle_func(*args, **kwargs)
File "C:\..\venv\lib\site-packages\django\core\management\commands\migrate.py", line 244, in handle
post_migrate_state = executor.migrate(
File "C:\..\venv\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:\..\venv\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:\..\venv\lib\site-packages\django\db\migrations\executor.py", line 227, in apply_migration
state = migration.apply(state, schema_editor)
File "C:\..\venv\lib\site-packages\django\db\migrations\migration.py", line 126, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "C:\..\venv\lib\site-packages\django\db\migrations\operations\fields.py", line 244, in database_forwards
schema_editor.alter_field(from_model, from_field, to_field)
File "C:\..\venv\lib\site-packages\django\db\backends\base\schema.py", line 608, in alter_field
self._alter_field(model, old_field, new_field, old_type, new_type,
File "C:\..\venv\lib\site-packages\django\db\backends\postgresql\schema.py", line 196, in _alter_field
super()._alter_field(
File "C:\..\venv\lib\site-packages\django\db\backends\base\schema.py", line 765, in _alter_field
self.execute(
File "C:\..\venv\lib\site-packages\django\db\backends\base\schema.py", line 145, in execute
cursor.execute(sql, params)
File "C:\..\venv\lib\site-packages\django\db\backends\utils.py", line 98, in execute
return super().execute(sql, params)
File "C:\..\venv\lib\site-packages\django\db\backends\utils.py", line 66, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "C:\..\venv\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\..\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\..\venv\lib\site-packages\django\db\utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\..\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: column "username" is in a primary key
I was thinking of solving this with raw SQL in the database, but I wasn't sure if that would cause further problems or not. I would much rather fix it with a django fix instead of raw sql
Hi AugustusCaesar,
When you remove UUID that time there UUID already migrated files present in migrations folder. So in a simple way, you on the local server first take backup then drop this database...
for backup.
pg_dumpall -U postgres > c:\pgbackup\all.sql
sudo su postgres
drop database database_name
psql livedx_qa < /home/Documents/database_name.sql <- again dump DB
python3 manage.py makemigrations
python3 manage.py migrate
I also face this issue you can use this solution. You can't delete manually migrations files this is not the right way so !!!!!
Thank You!!!
So I have this app I wish to deploy to Heroku. I use django-heroku so it can run my postgres-sql stuff automatically.
I added release: python mannge.py migrate to my Procfile.
After the build, I get a deployment failed error, saying Release command failed. On opening the log, I have this error:
psycopg2.ProgrammingError: cannot cast type timestamp with time zone to integer
LINE 1: ...LUMN "established" TYPE integer USING "established"::integer
^
My model with the established field is like this:
from django.db import models
# Create your models here.
class FederalMinistry(models.Model):
full_name = models.CharField(max_length=400)
short_name = models.CharField(max_length=20)
description = models.TextField()
established = models.PositiveIntegerField()
# logo = models.ImageField(upload_to='fed_min_logos', blank=True, null=True, default='N/A')
current_minister = models.CharField(max_length=500)
permanent_secretary = models.CharField(max_length=500, default='N\A')
headquarters = models.CharField(max_length=100, default='Abuja')
twitter = models.URLField(blank=True, null=True, default='N/A')
website = models.URLField(blank=True, null=True, default='N/A')
class Meta:
verbose_name_plural = 'Federal Ministries'
def __str__(self):
return self.full_name
Please why am I getting the error and his to fix it. I have no knowledge of postgres.
Here is the full traceback as was requested:
/app/.heroku/python/lib/python3.6/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>.
""")
Operations to perform:
Apply all migrations: admin, airports, auth, contenttypes, federal_ministries, sessions, states, universities
Running migrations:
Applying federal_ministries.0002_auto_20190310_0129...Traceback (most recent call last):
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
psycopg2.ProgrammingError: cannot cast type timestamp with time zone to integer
LINE 1: ...LUMN "established" TYPE integer USING "established"::integer
^
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 "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
utility.execute()
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 316, in run_from_argv
self.execute(*args, **cmd_options)
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 353, in execute
output = self.handle(*args, **options)
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped
res = handle_func(*args, **kwargs)
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 203, in handle
fake_initial=fake_initial,
File "/app/.heroku/python/lib/python3.6/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 "/app/.heroku/python/lib/python3.6/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 "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/executor.py", line 244, in apply_migration
state = migration.apply(state, schema_editor)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/migration.py", line 124, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/operations/fields.py", line 216, in database_forwards
schema_editor.alter_field(from_model, from_field, to_field)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 523, in alter_field
old_db_params, new_db_params, strict)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/postgresql/schema.py", line 122, in _alter_field
new_db_params, strict,
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 663, in _alter_field
params,
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 133, in execute
cursor.execute(sql, params)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 68, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/utils.py", line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
Q File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: cannot cast type timestamp with time zone to integer
LINE 1: ...LUMN "established" TYPE integer USING "established"::integer
And here is the federal_ministries.0002_auto_20190310_0129 migration file:
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('federal_ministries', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='federalministry',
options={'verbose_name_plural': 'Federal Ministries'},
),
migrations.AlterField(
model_name='federalministry',
name='established',
field=models.PositiveIntegerField(),
),
]
And the dependency 0001_initial file:
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='FederalMinistry',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('full_name', models.CharField(max_length=400)),
('short_name', models.CharField(max_length=20)),
('description', models.TextField()),
('established', models.DateTimeField()),
('current_minister', models.CharField(max_length=500)),
('permanent_secretary', models.CharField(default='N\\A', max_length=500)),
('headquarters', models.CharField(default='Abuja', max_length=100)),
('twitter', models.URLField(blank=True, default='N/A', null=True)),
('website', models.URLField(blank=True, default='N/A', null=True)),
],
),
]
I got it. I just needed to reset my migrations and delete the db.sqlite file, then ran migrations and migrate again. Fixed it!
If you are trying to cast a timestamp to PositiveIntegerField in PostgreSQL, you have to know that you can't.
Use a DateTimeField instead of a PositiveIntegerField for enstablished.
I think that this is related, take a look for further infos.
ive added a new app and created some models. I have run makemigrations and migrate and all went successfully. However when i open the sqlite table, none of the tables are created.
sample from models:
from __future__ import unicode_literals
from django.db import models
from django.conf import settings
import string
import random
import time
import os
# Create your models here.
from service.models import ServiceContacts
class Subnets(models.Model):
subnet = models.GenericIPAddressField(protocol='IPv4',verbose_name="Subnet",blank=True,null=True)
subnet_mask = models.CharField(max_length=4,verbose_name="Subnet Mask",choices=settings.SUBNET_MASK_CHOICES,blank=True)
subnet_type = models.CharField(max_length=10 ,verbose_name='Subnet Type',choices=settings.SUBNET_TYPE_CHOICES,blank=True)
class Meta:
verbose_name = "Site Subnet Data"
verbose_name_plural = "Site Subnet Data"
class SiteContacts(models.Model):
name = models.CharField(max_length=200)
title = models.CharField(max_length=200)
mobile = models.CharField(max_length=200,blank=True, null=True)
ddi = models.CharField(max_length=200,blank=True, null=True)
notes = models.TextField(blank=True, null=True)
class Meta:
verbose_name = "Site Contact Data"
verbose_name_plural = "Site Contact Data"
sample from inital
# -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-11-09 17:32
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import sites.models
class Migration(migrations.Migration):
initial = True
dependencies = [
('service', '0007_auto_20160701_0931'),
]
operations = [
migrations.CreateModel(
name='CircuitFiles',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('circuit_file', models.FileField(blank=True, upload_to=sites.models.service_upload_path)),
('file_name', models.CharField(max_length=200, verbose_name='File Name')),
],
options={
'verbose_name': 'Circuit Files',
'verbose_name_plural': 'Circuit Files',
},
),
migrations.CreateModel(
name='CircuitNotes',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('date', models.DateField()),
('notes', models.TextField(blank=True)),
],
options={
'verbose_name': 'Circuit Notes',
'verbose_name_plural': 'Circuit Notes',
},
),
tables from sqlite3db
[root#network-tools infternal]# sqlite3 db.sqlite3
SQLite version 3.7.17 2013-05-20 00:56:22
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> .tables
auth_group networks_circuitnotes
auth_group_permissions networks_configtemplates
auth_permission networks_configvariables
auth_user networks_majorsiteinfodata
auth_user_groups networks_networkstock
auth_user_user_permissions networks_networkstockusage
django_admin_log networks_showroomconfigdata
django_content_type networks_sitecontacts
django_migrations networks_sitefiles
django_session networks_sitefiletype
django_site networks_snmpdata
sqlite>
i should see sites_subnets and sites_sitecontacts in there, as well as many others.
the migrations table has the below in it, i cant see sites|0001_inital in there...
100|networks|0069_configvariables_type|2016-11-03 15:17:41.424747
101|networks|0070_circuitinfodata_circuit_preference|2016-11-09 09:11:29.358213
102|networks|0071_auto_20161109_0915|2016-11-09 09:15:22.455639
103|networks|0072_auto_20161109_0916|2016-11-09 09:16:25.962542
104|sites|0002_auto_20161110_0859|2016-11-10 08:59:31.071382
installed Apps:
INSTALLED_APPS = (
'home.apps.HomeConfig',
'oncall.apps.OncallConfig',
'networks.apps.NetworksConfig',
'sites.apps.SitesConfig',
Make Migrations:
[root#network-tools infternal]# python manage.py makemigrations
Migrations for 'networks':
0073_auto_20161110_1059.py:
- Alter field circuit_type on circuitinfodata
Migrations for 'sites':
0003_auto_20161110_1059.py:
- Alter field circuit_type on circuits
[root#network-tools infternal]# python manage.py migrate
Operations to perform:
Apply all migrations: service, sessions, admin, sites, auth, contenttypes, maintenance, oncall, networks
Running migrations:
Rendering model states... DONE
Applying networks.0073_auto_20161110_1059... OK
Applying sites.0003_auto_20161110_1059...Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/usr/lib64/python2.7/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line
utility.execute()
File "/usr/lib64/python2.7/site-packages/django/core/management/__init__.py", line 345, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/lib64/python2.7/site-packages/django/core/management/base.py", line 348, in run_from_argv
self.execute(*args, **cmd_options)
File "/usr/lib64/python2.7/site-packages/django/core/management/base.py", line 399, in execute
output = self.handle(*args, **options)
File "/usr/lib64/python2.7/site-packages/django/core/management/commands/migrate.py", line 200, in handle
executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial)
File "/usr/lib64/python2.7/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/lib64/python2.7/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/lib64/python2.7/site-packages/django/db/migrations/executor.py", line 198, in apply_migration
state = migration.apply(state, schema_editor)
File "/usr/lib64/python2.7/site-packages/django/db/migrations/migration.py", line 123, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "/usr/lib64/python2.7/site-packages/django/db/migrations/operations/fields.py", line 201, in database_forwards
schema_editor.alter_field(from_model, from_field, to_field)
File "/usr/lib64/python2.7/site-packages/django/db/backends/base/schema.py", line 482, in alter_field
old_db_params, new_db_params, strict)
File "/usr/lib64/python2.7/site-packages/django/db/backends/sqlite3/schema.py", line 253, in _alter_field
self._remake_table(model, alter_fields=[(old_field, new_field)])
File "/usr/lib64/python2.7/site-packages/django/db/backends/sqlite3/schema.py", line 184, in _remake_table
self.alter_db_table(model, temp_model._meta.db_table, model._meta.db_table)
File "/usr/lib64/python2.7/site-packages/django/db/backends/base/schema.py", line 359, in alter_db_table
"new_table": self.quote_name(new_db_table),
File "/usr/lib64/python2.7/site-packages/django/db/backends/base/schema.py", line 110, in execute
cursor.execute(sql, params)
File "/usr/lib64/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/usr/lib64/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/usr/lib64/python2.7/site-packages/django/db/utils.py", line 95, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/usr/lib64/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/usr/lib64/python2.7/site-packages/django/db/backends/sqlite3/base.py", line 323, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such table: sites_circuits
Try to migrate particular app using following process.
If you create initial migration and then run migrate command sometime migration not don completely so try to migrate using following command
python manage.py makemigrations
Initial migration created then run migrate command with app name
python manage.py migrate appname
Hope this is help you
ok heres what i did.
python manage.py sqlmigrate sites 0001
this gave me the sql for the migration, i then run
sqlite3 db.sqlite3
which opens the DB, i then just copied and pasted in the output from the sqlmigrate command into sql and its all working now
I'm trying to create ContentType reference (https://docs.djangoproject.com/en/1.8/ref/contrib/contenttypes/#generic-relations)
myobj/models.py:
from django.db import models
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
class TaggedItem(models.Model):
tag = models.SlugField()
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
When I start the test (manage.py test -v3), I get traceback:
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/home/alexander/.local/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
utility.execute()
File "/home/alexander/.local/lib/python2.7/site-packages/django/core/management/__init__.py", line 330, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/alexander/.local/lib/python2.7/site-packages/django/core/management/commands/test.py", line 30, in run_from_argv
super(Command, self).run_from_argv(argv)
File "/home/alexander/.local/lib/python2.7/site-packages/django/core/management/base.py", line 390, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/alexander/.local/lib/python2.7/site-packages/django/core/management/commands/test.py", line 74, in execute
super(Command, self).execute(*args, **options)
File "/home/alexander/.local/lib/python2.7/site-packages/django/core/management/base.py", line 441, in execute
output = self.handle(*args, **options)
File "/home/alexander/.local/lib/python2.7/site-packages/django/core/management/commands/test.py", line 90, in handle
failures = test_runner.run_tests(test_labels)
File "/home/alexander/.local/lib/python2.7/site-packages/django/test/runner.py", line 210, in run_tests
old_config = self.setup_databases()
File "/home/alexander/.local/lib/python2.7/site-packages/django/test/runner.py", line 166, in setup_databases
**kwargs
File "/home/alexander/.local/lib/python2.7/site-packages/django/test/runner.py", line 370, in setup_databases
serialize=connection.settings_dict.get("TEST", {}).get("SERIALIZE", True),
File "/home/alexander/.local/lib/python2.7/site-packages/django/db/backends/base/creation.py", line 368, in create_test_db
test_flush=True,
File "/home/alexander/.local/lib/python2.7/site-packages/django/core/management/__init__.py", line 120, in call_command
return command.execute(*args, **defaults)
File "/home/alexander/.local/lib/python2.7/site-packages/django/core/management/base.py", line 441, in execute
output = self.handle(*args, **options)
File "/home/alexander/.local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 179, in handle
created_models = self.sync_apps(connection, executor.loader.unmigrated_apps)
File "/home/alexander/.local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 317, in sync_apps
cursor.execute(statement)
File "/home/alexander/.local/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/home/alexander/.local/lib/python2.7/site-packages/django/db/utils.py", line 97, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/home/alexander/.local/lib/python2.7/site-packages/django/db/backends/utils.py", line 62, in execute
return self.cursor.execute(sql)
django.db.utils.ProgrammingError: ERROR: reference "django_content_type" does not exist
my settings.py:
...
INSTALLED_APPS = (
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.staticfiles',
'myobj',
)
...
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'mydb', # Or path to database file if using sqlite3.
'USER': 'user', # Not used with sqlite3.
'PASSWORD': 'pass', # Not used with sqlite3.
'HOST': '127.0.0.1', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '5432', # Set to empty string for default. Not used with sqlite3.
'TEST_NAME': "testdb_%i_%i" % (random.randrange(1,1000000),random.randrange(1,10000000)),
}
}
...
Postgresql log:
ALTER TABLE "myobj_taggeditem" ADD CONSTRAINT "myob_content_type_id_708726b4e928b107_fk_django_content_type_id" FOREIGN KEY ("content_type_id") REFERENCES "django_content_type" ("id") DEFERRABLE INITIALLY DEFERRED
ERROR: reference "django_content_type" does not exist
If I change DB engine to SQLite everythink is ok.
Whats wrong with it?
I'm using django 1.8
You must create migrations for your myobj app. An unmigrated app cannot depend on a migrated app.
Simply run python manage.py makemigrations myobj and it will create the initial migrations for your app.
The reason it "works" on SQLite3 is that foreign key constraints are not enforced in SQLite by Django.
I hoping that you can help me out. I currently have Django1.7 running on windows7/Java7/Jython2.7/Postgresql9.3/postgresql-9.3-1102.jdbc41.
I learned today that on Django 1.7 there is no reason to install the South package for migrations because 1.7 has makemigrations and migrate commands built in. But even so when I try to apply those commands in that order I am getting some sort of error. How can I resolve this error?
For more information on django migrations.
Django 1.7 Migrations
For more details about django on jython and the database settings.
postgresql on jython-django
My settings are:
DATABASES = {
'default': {
'ENGINE': 'doj.db.backends.postgresql',
'NAME': 'lwc',
'USER': 'lwc',
'PASSWORD': 'lwc',
'HOST': '127.0.0.1',
'PORT': '5432',
}
}
This is my models.py file and I am trying to add ip_address when I do the makemigrations and migrate commands.
from django.db import models
class Join(models.Model):
email = models.EmailField()
ip_address = models.CharField(max_length=120, null=True) #This is the new field
timestamp = models.DateTimeField(auto_now_add = True, auto_now=False)
updated = models.DateTimeField(auto_now_add = False, auto_now=True)
def __unicode__(self):
return "%s" %(self.email)
Here is the error that I get from running the migrate command:
C:\Users\mike\workspace\lwc>jython manage.py migrate
←[36;1mOperations to perform:←[0m
←[1m Apply all migrations: ←[0madmin, sessions, joins, auth, contenttypes
←[36;1mRunning migrations:←[0m
Applying joins.0003_join_ip_address...Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "C:\jython2.7b2\Lib\site-packages\django-1.7c3-py2.7.egg\django\core\mana
gement\__init__.py", line 385, in execute_from_command_line
utility.execute()
File "C:\jython2.7b2\Lib\site-packages\django-1.7c3-py2.7.egg\django\core\mana
gement\__init__.py", line 377, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\jython2.7b2\Lib\site-packages\django-1.7c3-py2.7.egg\django\core\mana
gement\base.py", line 288, in run_from_argv
self.execute(*args, **options.__dict__)
File "C:\jython2.7b2\Lib\site-packages\django-1.7c3-py2.7.egg\django\core\mana
gement\base.py", line 338, in execute
output = self.handle(*args, **options)
File "C:\jython2.7b2\Lib\site-packages\django-1.7c3-py2.7.egg\django\core\mana
gement\commands\migrate.py", line 160, in handle
executor.migrate(targets, plan, fake=options.get("fake", False))
File "C:\jython2.7b2\Lib\site-packages\django-1.7c3-py2.7.egg\django\db\migrat
ions\executor.py", line 63, in migrate
self.apply_migration(migration, fake=fake)
File "C:\jython2.7b2\Lib\site-packages\django-1.7c3-py2.7.egg\django\db\migrat
ions\executor.py", line 97, in apply_migration
migration.apply(project_state, schema_editor)
File "C:\jython2.7b2\Lib\site-packages\django-1.7c3-py2.7.egg\django\db\migrat
ions\migration.py", line 107, in apply
operation.database_forwards(self.app_label, schema_editor, project_state, ne
w_state)
File "C:\jython2.7b2\Lib\site-packages\django-1.7c3-py2.7.egg\django\db\migrat
ions\operations\fields.py", line 35, in database_forwards
schema_editor.add_field(
File "C:\jython2.7b2\Lib\site-packages\django-1.7c3-py2.7.egg\django\db\backen
ds\schema.py", line 411, in add_field
self.execute(sql, params)
File "C:\jython2.7b2\Lib\site-packages\django-1.7c3-py2.7.egg\django\db\backen
ds\schema.py", line 98, in execute
cursor.execute(sql, params)
File "C:\jython2.7b2\Lib\site-packages\django-1.7c3-py2.7.egg\django\db\backen
ds\utils.py", line 81, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "C:\jython2.7b2\Lib\site-packages\django-1.7c3-py2.7.egg\django\db\backen
ds\utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "C:\jython2.7b2\Lib\site-packages\django-1.7c3-py2.7.egg\django\db\utils.
py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "C:\jython2.7b2\Lib\site-packages\django-1.7c3-py2.7.egg\django\db\backen
ds\utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "C:\jython2.7b2\Lib\site-packages\django_jython-1.7.0b2-py2.7.egg\doj\db\
backends\__init__.py", line 180, in execute
self.cursor.execute(sql, params)
django.db.utils.Error: ERROR: could not determine data type of parameter $1 [SQL
Code: 0], [SQLState: 42P18]
I ran sqlmigrate because I understand that this is the sql calls that it is suppose to attempt to run. And I am not a DBA, but they don't look right to me. Anybody out there know SQL for Postgresql really well?
C:\Users\mike\workspace\lwc>jython manage.py sqlmigrate joins 0002_join_ref_
id
BEGIN;
ALTER TABLE `joins_join` ADD COLUMN `ref_id` varchar(120) DEFAULT "ABC" NOT NULL
;
ALTER TABLE `joins_join` ALTER COLUMN `ref_id` DROP DEFAULT;
COMMIT;
I tried running that command in the Postgresql Query tool and I got the following error:
ERROR: column "ABC" does not exist
********** Error **********
ERROR: column "ABC" does not exist
SQL state: 42703
So, then this looks like a bug with Django 1.7. Has anyone else had this issue? What is the correct SQL statement? How could I create a workaround or resolve this issue?