I have a problem concerning testing my app including migrations on ForeignKey modelfields having a default value (see example below, field mode in model RuleSet).
I don't know if that's a bug in Django 1.7 testing migrations or if I'm doing something wrong
#models.py:
RULE_SET_MODE__ACTIVE = "Active"
def default_mode():
return RuleSetMode.objects.get(name=RULE_SET_MODE__ACTIVE)
class RuleSetMode(models.Model):
name = models.CharField(max_length=30)
description = models.CharField(max_length=255)
class RuleSet(models.Model):
name = models.CharField(max_length=30, unique=True)
description = models.CharField(max_length=255)
mode = models.ForeignKey(RuleSetMode, default=default_mode)
I tried following migration steps so far:
created an initial migration with default value (function)
created an initial migration without default value and created a second migration changing the field by setting the default value
None of them worked for me. So you can see that the problem is not related to migrating the field itself. It's just related to the fact that migrations exists for the app.
(Overriding the save method would be a solution or disabling migrations during tests using this solution: Disable migrations when running unit tests in Django 1.7 , but I would prefer setting the default attribute)
#migrations file (altering the existing field):
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import myapp.models
class Migration(migrations.Migration):
dependencies = [
('myapp', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='ruleset',
name='mode',
field=models.ForeignKey(default=myapp.models.default_mode, to='myapp.RuleSetMode'),
),
]
The output executing: python manage.py test myapp:
Creating test database for alias 'default'...
Traceback (most recent call last):
File "manage.py", line 16, in <module>
execute_from_command_line(sys.argv)
File "/home/cgossy/venvs/django-1.7/local/lib/python2.7/site-packages/Django-1.7-py2.7.egg/django/core/management/__init__.py", line 385, in execute_from_command_line
utility.execute()
File "/home/cgossy/venvs/django-1.7/local/lib/python2.7/site-packages/Django-1.7-py2.7.egg/django/core/management/__init__.py", line 377, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/cgossy/venvs/django-1.7/local/lib/python2.7/site-packages/Django-1.7-py2.7.egg/django/core/management/commands/test.py", line 50, in run_from_argv
super(Command, self).run_from_argv(argv)
File "/home/cgossy/venvs/django-1.7/local/lib/python2.7/site-packages/Django-1.7-py2.7.egg/django/core/management/base.py", line 288, in run_from_argv
self.execute(*args, **options.__dict__)
File "/home/cgossy/venvs/django-1.7/local/lib/python2.7/site-packages/Django-1.7-py2.7.egg/django/core/management/commands/test.py", line 71, in execute
super(Command, self).execute(*args, **options)
File "/home/cgossy/venvs/django-1.7/local/lib/python2.7/site-packages/Django-1.7-py2.7.egg/django/core/management/base.py", line 338, in execute
output = self.handle(*args, **options)
File "/home/cgossy/venvs/django-1.7/local/lib/python2.7/site-packages/Django-1.7-py2.7.egg/django/core/management/commands/test.py", line 88, in handle
failures = test_runner.run_tests(test_labels)
File "/home/cgossy/venvs/django-1.7/local/lib/python2.7/site-packages/Django-1.7-py2.7.egg/django/test/runner.py", line 147, in run_tests
old_config = self.setup_databases()
File "/home/cgossy/venvs/django-1.7/local/lib/python2.7/site-packages/Django-1.7-py2.7.egg/django/test/runner.py", line 109, in setup_databases
return setup_databases(self.verbosity, self.interactive, **kwargs)
File "/home/cgossy/venvs/django-1.7/local/lib/python2.7/site-packages/Django-1.7-py2.7.egg/django/test/runner.py", line 299, in setup_databases
serialize=connection.settings_dict.get("TEST_SERIALIZE", True),
File "/home/cgossy/venvs/django-1.7/local/lib/python2.7/site-packages/Django-1.7-py2.7.egg/django/db/backends/creation.py", line 374, in create_test_db
test_flush=True,
File "/home/cgossy/venvs/django-1.7/local/lib/python2.7/site-packages/Django-1.7-py2.7.egg/django/core/management/__init__.py", line 115, in call_command
return klass.execute(*args, **defaults)
File "/home/cgossy/venvs/django-1.7/local/lib/python2.7/site-packages/Django-1.7-py2.7.egg/django/core/management/base.py", line 338, in execute
output = self.handle(*args, **options)
File "/home/cgossy/venvs/django-1.7/local/lib/python2.7/site-packages/Django-1.7-py2.7.egg/django/core/management/commands/migrate.py", line 160, in handle
executor.migrate(targets, plan, fake=options.get("fake", False))
File "/home/cgossy/venvs/django-1.7/local/lib/python2.7/site-packages/Django-1.7-py2.7.egg/django/db/migrations/executor.py", line 63, in migrate
self.apply_migration(migration, fake=fake)
File "/home/cgossy/venvs/django-1.7/local/lib/python2.7/site-packages/Django-1.7-py2.7.egg/django/db/migrations/executor.py", line 97, in apply_migration
migration.apply(project_state, schema_editor)
File "/home/cgossy/venvs/django-1.7/local/lib/python2.7/site-packages/Django-1.7-py2.7.egg/django/db/migrations/migration.py", line 107, in apply
operation.database_forwards(self.app_label, schema_editor, project_state, new_state)
File "/home/cgossy/venvs/django-1.7/local/lib/python2.7/site-packages/Django-1.7-py2.7.egg/django/db/migrations/operations/fields.py", line 131, in database_forwards
schema_editor.alter_field(from_model, from_field, to_field)
File "/home/cgossy/venvs/django-1.7/local/lib/python2.7/site-packages/Django-1.7-py2.7.egg/django/db/backends/schema.py", line 509, in alter_field
self._alter_field(model, old_field, new_field, old_type, new_type, old_db_params, new_db_params, strict)
File "/home/cgossy/venvs/django-1.7/local/lib/python2.7/site-packages/Django-1.7-py2.7.egg/django/db/backends/sqlite3/schema.py", line 183, in _alter_field
self._remake_table(model, alter_fields=[(old_field, new_field)])
File "/home/cgossy/venvs/django-1.7/local/lib/python2.7/site-packages/Django-1.7-py2.7.egg/django/db/backends/sqlite3/schema.py", line 121, in _remake_table
self.create_model(temp_model)
File "/home/cgossy/venvs/django-1.7/local/lib/python2.7/site-packages/Django-1.7-py2.7.egg/django/db/backends/schema.py", line 208, in create_model
definition, extra_params = self.column_sql(model, field)
File "/home/cgossy/venvs/django-1.7/local/lib/python2.7/site-packages/Django-1.7-py2.7.egg/django/db/backends/schema.py", line 120, in column_sql
default_value = self.effective_default(field)
File "/home/cgossy/venvs/django-1.7/local/lib/python2.7/site-packages/Django-1.7-py2.7.egg/django/db/backends/schema.py", line 170, in effective_default
default = field.get_default()
File "/home/cgossy/venvs/django-1.7/local/lib/python2.7/site-packages/Django-1.7-py2.7.egg/django/db/models/fields/related.py", line 1711, in get_default
field_default = super(ForeignKey, self).get_default()
File "/home/cgossy/venvs/django-1.7/local/lib/python2.7/site-packages/Django-1.7-py2.7.egg/django/db/models/fields/__init__.py", line 719, in get_default
return self.default()
File "/usr/local/lib/python2.7/dev-packages/kiola/kiola_alfred/models.py", line 33, in default_mode
return RuleSetMode.objects.get(name=RULE_SET_MODE__ACTIVE)
File "/home/cgossy/venvs/django-1.7/local/lib/python2.7/site-packages/Django-1.7-py2.7.egg/django/db/models/manager.py", line 92, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/cgossy/venvs/django-1.7/local/lib/python2.7/site-packages/Django-1.7-py2.7.egg/django/db/models/query.py", line 357, in get
self.model._meta.object_name)
myapp.models.DoesNotExist: RuleSetMode matching query does not exist.
Any ideas are welcome
I found a solution for my problem.
The problem is that the data base is - of course- empty while migrations are applied. Since
migrations.AlterField(
model_name='ruleset',
name='mode',
field=models.ForeignKey(default=myapp.models.default_mode, to='myapp.RuleSetMode'),
),
uses
models.ForeignKey(default=myapp.models.default_mode, to='myapp.RuleSetMode')
the function used for setting the default value is executed. But there is no value in the Database.
Now I added a data migration between initial migration and the migration which adds the default value.
This looks like that:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
def set_default_values(apps, schema_editor):
# We can't import the Person model directly as it may be a newer
# version than this migration expects. We use the historical version.
import myapp.const as const
RuleSetMode = apps.get_model("myapp", "RuleSetMode")
RuleSetMode.objects.get_or_create(name=const.RULE_SET_MODE__ACTIVE)
class Migration(migrations.Migration):
dependencies = [
('myapp', '0001_initial'),
]
operations = [
migrations.RunPython(set_default_values),
]
and in the migration which adds the default value gets the dependency list is changed to:
dependencies = [
('myapp', '0002_auto_20140925_1458'),
]
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!!!
I would like to create a custom queryset for my User model.
However, I cannot simply use objects = UserQuerySet.as_manager() since the standard Django User model already has a custom UserManager.
My code is simply :
class UserQuerySet(MyBaseQuerySet):
def opted_out_method(self):
return
class User(AbstractUser):
objects = UserManager.from_queryset(UserQuerySet)()
# etc...
This code works, except when I do this:
$manage.py makemigrations --dry-run
File "./manage.py", line 49, in <module>
execute_from_command_line(sys.argv)
File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
utility.execute()
File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/core/management/__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/core/management/base.py", line 323, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/core/management/base.py", line 364, in execute
output = self.handle(*args, **options)
File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/core/management/base.py", line 83, in wrapped
res = handle_func(*args, **kwargs)
File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/core/management/commands/makemigrations.py", line 164, in handle
changes = autodetector.changes(
File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/db/migrations/autodetector.py", line 43, in changes
changes = self._detect_changes(convert_apps, graph)
File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/db/migrations/autodetector.py", line 129, in _detect_changes
self.new_apps = self.to_state.apps
File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/utils/functional.py", line 80, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/db/migrations/state.py", line 210, in apps
return StateApps(self.real_apps, self.models)
File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/db/migrations/state.py", line 273, in __init__
self.render_multiple([*models.values(), *self.real_models])
File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/db/migrations/state.py", line 308, in render_multiple
model.render(self)
File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/db/migrations/state.py", line 577, in render
body.update(self.construct_managers())
File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/db/migrations/state.py", line 536, in construct_managers
as_manager, manager_path, qs_path, args, kwargs = manager.deconstruct()
File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/db/models/manager.py", line 61, in deconstruct
raise ValueError(
The exception raised is "Could not find manager. Please note that you need to inherit from managers you dynamically generated with 'from_queryset()", which is what I'm doing.
Has anyone run into this before?
I'm currently using Django 2.2, not sure if this is fixed in 3+.
The solution is to create a custom manager that derives from UserManager.
from django.contrib.auth.models import UserManager
class MyCustomUserManager(UserManager):
def bob_filter(self):
return super().get_queryset().filter(first_name__icontains="bob")
# etc...
class User(AbstractUser):
objects = managers.CustomUserManager()
# etc...
I have a problem with two of my models. When tying to migrate it always ends up with the error that I have more than one primary key. I have googled and tried lots of different solutions but nothing works.
models: notice the imports
from django.db.models import Model,CharField,EmailField,IntegerField,\
OneToOneField,CASCADE,DateTimeField,ForeignKey,BooleanField,\
IntegerField,SlugField
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _
from phone_field import PhoneField
from datetime import datetime
from pdb import set_trace as B
class Adress(Model):
street=CharField(default='',max_length=100)
snumb=CharField(default='',max_length=15)
town=CharField(default='',max_length=100)
postn=CharField(default='',max_length=5,validators=[postnvali])
def __str__(self):
return 'city: ' + self.town
class Meta:
ordering=('street','town')
class Person(Model):
fname=CharField(default="",max_length=100)
lname=CharField(default="",max_length=100)
mobil=PhoneField(default='9999999999')
mail=EmailField(default='contact#gmail.com')
padress=OneToOneField(Adress,on_delete=CASCADE)
def __str__(self):
return 'person: ' + self.fname
class Meta:
ordering=('fname','lname')
migration file:
# Generated by Django 3.1.4 on 2021-01-20 13:32
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('kammem', '0029_auto_20210120_1354'),
]
operations = [
migrations.AddField(
model_name='person',
name='id',
field=models.AutoField(auto_created=True,serialize=False, verbose_name='ID'),
preserve_default=False,
),
migrations.AlterField(
model_name='person',
name='padress',
field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='kammem.adress'),
),
]
Try to change your migration file to this and then run migrate:
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('kammem', '0029_auto_20210120_1354'),
]
operations = [
migrations.AlterField(
model_name='person',
name='padress',
field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='kammem.adress'),
),
]
ok, here is the full error traceback:
jonas#192.168.1.133 kammem $ python3 manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, kammem, sessions
Running migrations:
Applying kammem.0025_auto_20210120_0935...Traceback (most recent call last):
File "/home/jonas/.local/lib/python3.9/site-packages/django/db/backends/utils.py", line 82, in _execute
return self.cursor.execute(sql)
File "/home/jonas/.local/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py", line 411, in execute
return Database.Cursor.execute(self, query)
sqlite3.OperationalError: table "new__kammem_person" has more than one primary key
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/jonas/Dropbox/prog/web/django/kammem/manage.py", line 22, in <module>
main()
File "/home/jonas/Dropbox/prog/web/django/kammem/manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "/home/jonas/.local/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
utility.execute()
File "/home/jonas/.local/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/jonas/.local/lib/python3.9/site-packages/django/core/management/base.py", line 330, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/jonas/.local/lib/python3.9/site-packages/django/core/management/base.py", line 371, in execute
output = self.handle(*args, **options)
File "/home/jonas/.local/lib/python3.9/site-packages/django/core/management/base.py", line 85, in wrapped
res = handle_func(*args, **kwargs)
File "/home/jonas/.local/lib/python3.9/site-packages/django/core/management/commands/migrate.py", line 243, in handle
post_migrate_state = executor.migrate(
File "/home/jonas/.local/lib/python3.9/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/jonas/.local/lib/python3.9/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/jonas/.local/lib/python3.9/site-packages/django/db/migrations/executor.py", line 227, in apply_migration
state = migration.apply(state, schema_editor)
File "/home/jonas/.local/lib/python3.9/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/jonas/.local/lib/python3.9/site-packages/django/db/migrations/operations/fields.py", line 236, in database_forwards
schema_editor.alter_field(from_model, from_field, to_field)
File "/home/jonas/.local/lib/python3.9/site-packages/django/db/backends/sqlite3/schema.py", line 138, in alter_field
super().alter_field(model, old_field, new_field, strict=strict)
File "/home/jonas/.local/lib/python3.9/site-packages/django/db/backends/base/schema.py", line 571, in alter_field
self._alter_field(model, old_field, new_field, old_type, new_type,
File "/home/jonas/.local/lib/python3.9/site-packages/django/db/backends/sqlite3/schema.py", line 360, in _alter_field
self._remake_table(model, alter_field=(old_field, new_field))
File "/home/jonas/.local/lib/python3.9/site-packages/django/db/backends/sqlite3/schema.py", line 280, in _remake_table
self.create_model(new_model)
File "/home/jonas/.local/lib/python3.9/site-packages/django/db/backends/base/schema.py", line 324, in create_model
self.execute(sql, params or None)
File "/home/jonas/.local/lib/python3.9/site-packages/django/db/backends/base/schema.py", line 142, in execute
cursor.execute(sql, params)
File "/home/jonas/.local/lib/python3.9/site-packages/django/db/backends/utils.py", line 98, in execute
return super().execute(sql, params)
File "/home/jonas/.local/lib/python3.9/site-packages/django/db/backends/utils.py", line 66, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/home/jonas/.local/lib/python3.9/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/home/jonas/.local/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "/home/jonas/.local/lib/python3.9/site-packages/django/db/utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/home/jonas/.local/lib/python3.9/site-packages/django/db/backends/utils.py", line 82, in _execute
return self.cursor.execute(sql)
File "/home/jonas/.local/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py", line 411, in execute
return Database.Cursor.execute(self, query)
django.db.utils.OperationalError: table "new__kammem_person" has more than one primary key
ok, I think I solved it by simply removing all migrationsfiles and then rerun make migrations and migrate. Still, this is a common problem according to my google searches.
After importing Psycopg2==2.7.4 into my server, I can no longer run my server properly. After adding new fields, this is what happens now in my terminal whenever I try to make migrate after makemigrations(python manage.py migrate):
Apply all migrations: admin, auth, buddysapp, contenttypes, oauth2_provider, sessions, social_django
Running migrations:
Applying buddysapp.0038_auto_20180321_0025...Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/Users/hsi/Desktop/myvirtualenv/buddys/lib/python3.6/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line
utility.execute()
File "/Users/hsi/Desktop/myvirtualenv/buddys/lib/python3.6/site-packages/django/core/management/__init__.py", line 359, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/hsi/Desktop/myvirtualenv/buddys/lib/python3.6/site-packages/django/core/management/base.py", line 305, in run_from_argv
self.execute(*args, **cmd_options)
File "/Users/hsi/Desktop/myvirtualenv/buddys/lib/python3.6/site-packages/django/core/management/base.py", line 356, in execute
output = self.handle(*args, **options)
File "/Users/hsi/Desktop/myvirtualenv/buddys/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 202, in handle
targets, plan, fake=fake, fake_initial=fake_initial
File "/Users/hsi/Desktop/myvirtualenv/buddys/lib/python3.6/site-packages/django/db/migrations/executor.py", line 97, in migrate
state = self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_initial)
File "/Users/hsi/Desktop/myvirtualenv/buddys/lib/python3.6/site-packages/django/db/migrations/executor.py", line 132, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
File "/Users/hsi/Desktop/myvirtualenv/buddys/lib/python3.6/site-packages/django/db/migrations/executor.py", line 237, in apply_migration
state = migration.apply(state, schema_editor)
File "/Users/hsi/Desktop/myvirtualenv/buddys/lib/python3.6/site-packages/django/db/migrations/migration.py", line 129, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "/Users/hsi/Desktop/myvirtualenv/buddys/lib/python3.6/site-packages/django/db/migrations/operations/fields.py", line 84, in database_forwards
field,
File "/Users/hsi/Desktop/myvirtualenv/buddys/lib/python3.6/site-packages/django/db/backends/sqlite3/schema.py", line 231, in add_field
self._remake_table(model, create_fields=[field])
File "/Users/hsi/Desktop/myvirtualenv/buddys/lib/python3.6/site-packages/django/db/backends/sqlite3/schema.py", line 113, in _remake_table
self.effective_default(field)
File "/Users/hsi/Desktop/myvirtualenv/buddys/lib/python3.6/site-packages/django/db/backends/sqlite3/schema.py", line 68, in quote_value
raise ValueError("Cannot quote parameter value %r of type %s" % (value, type(value)))
ValueError: Cannot quote parameter value <psycopg2._json.Json object at 0x10ea5e748> of type <class 'psycopg2._json.Json'>
Any ideas, let me know.
Update: Migration file 0038
rom __future__ import unicode_literals
import buddysapp.models
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('buddysapp', '0037_auto_20180318_1816'),
]
operations = [
migrations.AddField(
model_name='dispensary',
name='businessHours',
field=django.contrib.postgres.fields.jsonb.JSONField(blank=True, default=buddysapp.models.business_hours_default, null=True),
),
migrations.AlterField(
model_name='order',
name='status',
field=models.IntegerField(choices=[(1, 'Your Order Is Being Picked Right Off The Plant!'), (2, 'Picked, Weighed, And Ready For Delivery.'), (3, 'The Best Bud Is Heading Straight To Your Door.'), (4, 'Delivered'), (0, 'Canceled/Refunded')]),
),
]
You can’t use a JSONField from django.contrib.postgres with an Sqlite3 database.
You need to either set up a PostgreSQL database and update your DATABASES setting, or use a different field in your model.
I'm trying to create to index pages that are children of home page, some like this:
# -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2017-11-13 22:50
from __future__ import unicode_literals
from django.db import migrations
def create_blogindexpage(apps, schema_editor):
# Get models
ContentType = apps.get_model('contenttypes.ContentType')
BlogIndexPage = apps.get_model('blog.BlogIndexPage')
HomePage = apps.get_model('home.HomePage')
blogindexpage_content_type, __ = ContentType.objects.get_or_create(
model='blogindexpage', app_label='blog')
# Create a new blogindexpage
blogindexpage = BlogIndexPage.objects.create(
title="Blogs",
draft_title="Blogs",
slug='blogs',
content_type=blogindexpage_content_type,
path='000100010001',
depth=3,
numchild=0,
url_path='/blogs/',
)
home_page = HomePage.objects.get(id=3)
home_page.add_child(instance=blogindexpage)
class Migration(migrations.Migration):
dependencies = [
('blog', '0001_initial'),
('home', '0002_create_homepage'),
]
operations = [
migrations.RunPython(
create_blogindexpage,
),
]
This index of blogs have to be a child from the home page and this migration file depends of home create_homepage migration, but it give me this error:
File "./manage.py", line 12, in <module>
execute_from_command_line(sys.argv)
File "/home/salahaddin/Proyectos/Works/partnerlatam/blog.xprende/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line
utility.execute()
File "/home/salahaddin/Proyectos/Works/partnerlatam/blog.xprende/lib/python3.6/site-packages/django/core/management/__init__.py", line 356, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/salahaddin/Proyectos/Works/partnerlatam/blog.xprende/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/salahaddin/Proyectos/Works/partnerlatam/blog.xprende/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute
output = self.handle(*args, **options)
File "/home/salahaddin/Proyectos/Works/partnerlatam/blog.xprende/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 204, in handle
fake_initial=fake_initial,
File "/home/salahaddin/Proyectos/Works/partnerlatam/blog.xprende/lib/python3.6/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 "/home/salahaddin/Proyectos/Works/partnerlatam/blog.xprende/lib/python3.6/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 "/home/salahaddin/Proyectos/Works/partnerlatam/blog.xprende/lib/python3.6/site-packages/django/db/migrations/executor.py", line 244, in apply_migration
state = migration.apply(state, schema_editor)
File "/home/salahaddin/Proyectos/Works/partnerlatam/blog.xprende/lib/python3.6/site-packages/django/db/migrations/migration.py", line 129, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "/home/salahaddin/Proyectos/Works/partnerlatam/blog.xprende/lib/python3.6/site-packages/django/db/migrations/operations/special.py", line 193, in database_forwards
self.code(from_state.apps, schema_editor)
File "/home/salahaddin/Proyectos/Works/partnerlatam/blog.xprende/xprende/blog/migrations/0002_create_blogindexpage.py", line 30, in create_blogindexpage
home_page.add_child(instance=blogindexpage)
AttributeError: 'HomePage' object has no attribute 'add_child'
I can't understand why i have this bug. I need to create this page and make them children from home page, how can i do that?
UPDATE:
I solved this question using this:
def create_blogindexpage(apps, schema_editor):
from home.models import HomePage
# Get models
ContentType = apps.get_model('contenttypes.ContentType')
BlogIndexPage = apps.get_model('blog.BlogIndexPage')
blogindexpage_content_type, __ = ContentType.objects.get_or_create(
model='blogindexpage', app_label='blog')
home_page = HomePage.objects.get(id=3)
home_page.add_child(
instance=BlogIndexPage(
title="Blogs",
draft_title="Blogs",
slug='blogs',
content_type=blogindexpage_content_type,
numchild=0,
url_path='/blogs/',
)
)
It isn't the properly way but, if you can see my comments, i don't know how can i do it using move function.