I have a problem with Django migrations on empty DB. When I want to migrate I have a circular dependency error. Circular dependency error between two apps that related by foreign keys
/firstapp/models.py
class Person(models.Model):
...
class Doctor(Person):
hospital = models.ForeignKey('hospital.Hospital', on_delete=models.SET_NULL, null=True, default=None,blank = True)
...
class Patient(Person):
doctor = models.ForeignKey('Doctor', on_delete=models.SET_NULL, null=True, default=None)
/secondapp/models.py
class Hospital(models.Model):
...
main_doctor = models.ForeignKey('authoriz.Doctor', on_delete=models.SET_NULL, null=True,verbose_name="Main Doctor")
calendar = models.ForeignKey('schedule.Calendar',verbose_name="calendar",null = True)
...
class Seat(models.Model):
hospital = models.ForeignKey('Hospital', on_delete=models.CASCADE)
...
After
python manage.py migrate
Traceback
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/home/user/project/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line
utility.execute()
File "/home/user/project/lib/python3.5/site-packages/django/core/management/__init__.py", line 359, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/user/project/lib/python3.5/site-packages/django/core/management/base.py", line 305, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/user/project/lib/python3.5/site-packages/django/core/management/base.py", line 356, in execute
output = self.handle(*args, **options)
File "/home/user/project/lib/python3.5/site-packages/django/core/management/commands/migrate.py", line 136, in handle
plan = executor.migration_plan(targets)
File "/home/user/project/lib/python3.5/site-packages/django/db/migrations/executor.py", line 60, in migration_plan
for migration in self.loader.graph.forwards_plan(target):
File "/home/user/project/lib/python3.5/site-packages/django/db/migrations/graph.py", line 280, in forwards_plan
self.ensure_not_cyclic(target, lambda x: (parent.key for parent in self.node_map[x].parents))
File "/home/user/project/lib/python3.5/site-packages/django/db/migrations/graph.py", line 370, in ensure_not_cyclic
raise CircularDependencyError(", ".join("%s.%s" % n for n in cycle))
django.db.migrations.exceptions.CircularDependencyError: authoriz.0001_initial, hospital.0001_initial
Thanks for help.
Temporarily comment out foreign keys to break the circular dependency. It looks like you could do this by commenting out Hospital.doctor. Remove the existing migrations and run makemigrations to recreate them.
Finally, uncomment the foreign keys, and run makemigrations again. You should end up with migrations without any circular dependencies.
Should be useful if you add your Calendar model. However don't use the inheritance without abstract modal.
class Person(models.Model):
...
class Meta:
abstract = True
Like you might have defined them as something below:
new_field = models.ForeignKey(ForeignModel, ...)
Instead do this:
new_field = models.ForeignKey("ForeignModel", ...)
Related
I am working with django-tenant-schemas and when I try to use "migrate_schemas" command I encounter an error. I've seen similar questions here but they didn't help at all. I've tried this on two different apps but the result is the same. Does anybody know how to fix this?
Traceback (most recent call last):
File "C:\DjangoNew\tenancy\manage.py", line 22, in <module>
main()
File "C:\DjangoNew\tenancy\manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "C:\Users\asyey\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line
utility.execute()
File "C:\Users\asyey\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\asyey\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 322, in run_from_argv
parser = self.create_parser(argv[0], argv[1])
File "C:\Users\asyey\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 296, in create_parser
self.add_arguments(parser)
File "C:\Users\asyey\AppData\Local\Programs\Python\Python37\lib\site-packages\tenant_schemas\management\commands\migrate_schemas.py", line 20, in add_arguments
command.add_arguments(parser)
File "C:\Users\asyey\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\commands\migrate.py", line 28, in add_arguments
help='Skip system checks.',
File "C:\Users\asyey\AppData\Local\Programs\Python\Python37\lib\argparse.py", line 1373, in add_argument
return self._add_action(action)
File "C:\Users\asyey\AppData\Local\Programs\Python\Python37\lib\argparse.py", line 1736, in _add_action
self._optionals._add_action(action)
File "C:\Users\asyey\AppData\Local\Programs\Python\Python37\lib\argparse.py", line 1577, in _add_action
action = super(_ArgumentGroup, self)._add_action(action)
File "C:\Users\asyey\AppData\Local\Programs\Python\Python37\lib\argparse.py", line 1387, in _add_action
self._check_conflict(action)
File "C:\Users\asyey\AppData\Local\Programs\Python\Python37\lib\argparse.py", line 1526, in _check_conflict
conflict_handler(action, confl_optionals)
File "C:\Users\asyey\AppData\Local\Programs\Python\Python37\lib\argparse.py", line 1535, in _handle_conflict_error
raise ArgumentError(action, message % conflict_string)
argparse.ArgumentError: argument --skip-checks: conflicting option string: --skip-checks
It is a bug in django-tenant-schemas.
From reading Django documents it seems like they forgot to set requires_system_checks to False.
I believe this pull request will fix the problem.
Till this fix is merged, you can solve this by either downgrade Django to version 2 by running something like
pip install "Django~=2.2"
or move tenant-schemas at the INSTALLED_APPS list to the bottom in the settings.py file.
Error: argparse.ArgumentError: argument --email: conflicting option string: --email
If anyone here by this error from django-rest-framework
So, this error occurs because the field 'email' is required, but still in Model's REQUIRED_FIELDS list.
Just remove it from REQUIRED_FIELDS, it should work.
This scenario also possible in other attributes also.
class UserAccount(AbstractUser):
first_name = ...
last_name = ...
email = models.EmailField(_("Email address"), unique=True, blank=False)
REQUIRED_FIELDS = AbstractUser.REQUIRED_FIELDS + ['first_name', 'last_name', 'email']
class Meta(AbstractUser.Meta):
swappable = "AUTH_USER_MODEL"
verbose_name = _("UserAccount")
verbose_name_plural = _("UserAccounts")
I have a model called "Employment" in my app, which references two models called "User" and "Company". In the Employments table in the database, there is a composite index on the two foreign keys preventing the same user from having two employments with the same company. I am trying to represent this composite index in Django using the UniqueConstraint class, but it is throwing an error which I cannot find any documentation for.
This model usually works perfectly fine. However, when I add the UniqueConstraint to the model's indexes, the server throws an error. I've looked at the documentation for UniqueConstraint, as well as the rest of Django's documentation, but could not find any mentions of the error I receive. I've also tried replacing 'User_ID' and 'Company_ID' with 'user' and 'company' in the fields argument for UniqueConstraint, but I obtained the exact same error.
Not sure if this is relevant to the issue, but I'm running the Django server with Docker in a python:3.6 container with Django version 2.2.
Here is the Employment model:
from django.db import models
from app.models import User, Company
class Employment(models.Model):
Employment_ID = models.AutoField(primary_key=True)
user = models.ForeignKey(User, db_column='User_ID', on_delete=models.CASCADE)
company = models.ForeignKey(Company, db_column='Company_ID', on_delete=models.CASCADE)
class Meta:
db_table = "Employments"
indexes = [
models.UniqueConstraint(fields=['User_ID', 'Company_ID'],
name='Employment_User_Company_UNIQUE') # server works fine without this
]
When I start my Django server, I get the following output:
Watching for file changes with StatReloader
Performing system checks...
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/local/lib/python3.6/threading.py", line 916, in _bootstrap_inner
self.run()
File "/usr/local/lib/python3.6/threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "/usr/local/lib/python3.6/site-packages/django/utils/autoreload.py", line 54, in wrapper
fn(*args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run
self.check(display_num_errors=True)
File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 390, in check
include_deployment_checks=include_deployment_checks,
File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 377, in _run_checks
return checks.run_checks(**kwargs)
File "/usr/local/lib/python3.6/site-packages/django/core/checks/registry.py", line 72, in run_checks
new_errors = check(app_configs=app_configs)
File "/usr/local/lib/python3.6/site-packages/django/core/checks/model_checks.py", line 31, in check_all_models
errors.extend(model.check(**kwargs))
File "/usr/local/lib/python3.6/site-packages/django/db/models/base.py", line 1254, in check
*cls._check_indexes(),
File "/usr/local/lib/python3.6/site-packages/django/db/models/base.py", line 1565, in _check_indexes
fields = [field for index in cls._meta.indexes for field, _ in index.fields_orders]
File "/usr/local/lib/python3.6/site-packages/django/db/models/base.py", line 1565, in <listcomp>
fields = [field for index in cls._meta.indexes for field, _ in index.fields_orders]
AttributeError: 'UniqueConstraint' object has no attribute 'fields_orders'
If anyone has experienced this error or knows of a workaround, I would be very grateful for your insight.
You defined this in the indexes parameter, but this should be in the constraints [Django-doc] attribute. indexes contains, as the name suggests, the list of indexes defined on the table. constraints on the other hand contains the constraints that should be enforced.
class Employment(models.Model):
Employment_ID = models.AutoField(primary_key=True)
user = models.ForeignKey(User, db_column='User_ID', on_delete=models.CASCADE)
company = models.ForeignKey(Company, db_column='Company_ID', on_delete=models.CASCADE)
class Meta:
db_table = "Employments"
constraints = [
models.UniqueConstraint(
fields=['User_ID', 'Company_ID'],
name='Employment_User_Company_UNIQUE'
)
]
So I have been trying to implement a way to upload multiple images to a post. The way I did it is to have tables. One for the actual post, and one of the multiple images uploaded. I was planning to link them with a foreign key but it is not working. My terminal started throwing the error "TypeError: id() takes exactly one argument (0 given)" . It throws me this error whenever I migrate it.
I am not sure how to fix this.
MY code:
models.py
from django.db import models
from django.utils import timezone
from django.forms import ModelForm
from django.utils.text import slugify
from django.utils.crypto import get_random_string
from django.conf import settings
from PIL import Image
import os
DEFAULT_IMAGE_ID = 1
# Create your models here.
class Projects(models.Model):
title = models.CharField(max_length=30)
description = models.TextField(max_length=150)
publish_date = models.DateTimeField(auto_now=False, auto_now_add=True)
update_date = models.DateTimeField(auto_now=True, auto_now_add=False)
slug = models.SlugField(unique=True)
files = models.FileField(upload_to='files/', blank=True)
images = models.ImageField(upload_to='images/', height_field = 'img_height', width_field = 'img_width',blank=True)
img_height = models.PositiveIntegerField(default=600)
img_width = models.PositiveIntegerField(default=300)
#feature_images = models.ForeignKey(P_Images, on_delete=models.CASCADE, default=DEFAULT_IMAGE_ID)
feature_images = models.AutoField(primary_key=True)
def __str__(self):
return self.title
def save(self, *args, **kwargs):
# Generates a random string
unique_string = get_random_string(length=32)
# Combines title and unique string to slugify
slugtext = self.title + "-" + "unique_id=-" + unique_string
self.slug = slugify(slugtext)
return super(Projects, self).save(*args, **kwargs)
class P_Images(models.Model):
p_file = models.ImageField(upload_to='images/', blank=None)
p_uploaded_at = models.DateTimeField(auto_now_add=True, auto_now=False)
#fk_post = models
fk_post = models.ForeignKey(Projects, on_delete=models.CASCADE)
The errorlog
Operations to perform:
Apply all migrations: admin, auth, contenttypes, projects, sessions
Running migrations:
Applying projects.0005_auto_20180823_0553...Traceback (most recent call last):
File "manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "/home/erichardson/env01/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
utility.execute()
File "/home/erichardson/env01/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/erichardson/env01/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/erichardson/env01/lib/python3.6/site-packages/django/core/management/base.py", line 335, in execute
output = self.handle(*args, **options)
File "/home/erichardson/env01/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 200, in handle
fake_initial=fake_initial,
File "/home/erichardson/env01/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 "/home/erichardson/env01/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 "/home/erichardson/env01/lib/python3.6/site-packages/django/db/migrations/executor.py", line 244, in apply_migration
state = migration.apply(state, schema_editor)
File "/home/erichardson/env01/lib/python3.6/site-packages/django/db/migrations/migration.py", line 122, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "/home/erichardson/env01/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 "/home/erichardson/env01/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 525, in alter_field
old_db_params, new_db_params, strict)
File "/home/erichardson/env01/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 630, in _alter_field
new_default = self.effective_default(new_field)
File "/home/erichardson/env01/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 218, in effective_default
default = field.get_default()
File "/home/erichardson/env01/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 775, in get_default
return self._get_default()
TypeError: id() takes exactly one argument (0 given)
I use a MySQL database for this. This error started popping up after I updated my tables to be able to link with each other. I plan the fk_post of the P_Images to contain the feature_image value of Projects for the foreign key.
005_migration.py
import builtins
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('projects', '0004_auto_20180823_0547'),
]
operations = [
migrations.AlterField(
model_name='p_images',
name='fk_post',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='projects.Projects'),
),
migrations.AlterField(
model_name='projects',
name='feature_images',
field=models.IntegerField(default=builtins.id),
),
]
please let me know if the migration.py tells you something or nothing.
You have something very bizarre in your migration:
models.IntegerField(default=builtins.id)
This is referring to the builtin id function, which requires an argument because it returns the internal ID of an object in Python. It has nothing to do with database IDs, and doesn't belong here at all. I can only guess that you were asked for a default when creating the migration and you just typed in id.
You should delete that default from the migration, but that may make it unable to execute. You could also try a default of 0, which makes sense there; but your actual models code shows that field as the primary key, so you presumably have another subsequent migration that changes the field again; and 0 wouldn't work as a pk.
If you're still in development and don't have any data you need to keep, I would suggest deleting your database and migrations completely and starting again with makemigrations.
I think this error occurred because you haven't set a default value to your foreign key. For your previous P_Images instances (before your current migration), they don't have a Projects id related to them.
The error text shown also confirms it:
return self._get_default()
TypeError: id() takes exactly one argument (0 given)
So try adding a default value :
DEFAULT_PROJECT = 1 # or the id of any project that does exist
fk_post = models.ForeignKey(Projects, on_delete=models.CASCADE, default = DEFAULT_PROJECT)
In Django 1.9 using SQLite as the database backend, I am getting an error when trying to apply migrations after modifying a model to use multi-table inheritance instead of the OneToOneField relationship it was previously using.
Particularly, the problem seems to be due to including a ForeignKey('self') in the model.
models.py
Here is the app from which an initial migration is successfully made and applied:
from django.db import models
from django.contrib.auth.models import User
class Customer(models.Model):
account = models.OneToOneField(User)
parent = models.ForeignKey('self', null=True)
models.py (modified)
The app is then modified to inherit from the User model rather than linking to it:
from django.db import models
from django.contrib.auth.models import User
class Customer(User):
parent = models.ForeignKey('self', null=True)
At this point a ./manage.py makemigrations <app> succeeds but then applying the migration fails with:
Error
Traceback (most recent call last):
File "./manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/home/piranha/.virtualenvs/Python_3.5-Django_1.9/lib/python3.5/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line
utility.execute()
File "/home/piranha/.virtualenvs/Python_3.5-Django_1.9/lib/python3.5/site-packages/django/core/management/__init__.py", line 345, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/piranha/.virtualenvs/Python_3.5-Django_1.9/lib/python3.5/site-packages/django/core/management/base.py", line 348, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/piranha/.virtualenvs/Python_3.5-Django_1.9/lib/python3.5/site-packages/django/core/management/base.py", line 399, in execute
output = self.handle(*args, **options)
File "/home/piranha/.virtualenvs/Python_3.5-Django_1.9/lib/python3.5/site-packages/django/core/management/commands/migrate.py", line 200, in handle
executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial)
File "/home/piranha/.virtualenvs/Python_3.5-Django_1.9/lib/python3.5/site-packages/django/db/migrations/executor.py", line 92, in migrate
self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_initial)
File "/home/piranha/.virtualenvs/Python_3.5-Django_1.9/lib/python3.5/site-packages/django/db/migrations/executor.py", line 121, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
File "/home/piranha/.virtualenvs/Python_3.5-Django_1.9/lib/python3.5/site-packages/django/db/migrations/executor.py", line 198, in apply_migration
state = migration.apply(state, schema_editor)
File "/home/piranha/.virtualenvs/Python_3.5-Django_1.9/lib/python3.5/site-packages/django/db/migrations/migration.py", line 123, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "/home/piranha/.virtualenvs/Python_3.5-Django_1.9/lib/python3.5/site-packages/django/db/migrations/operations/fields.py", line 62, in database_forwards
field,
File "/home/piranha/.virtualenvs/Python_3.5-Django_1.9/lib/python3.5/site-packages/django/db/backends/sqlite3/schema.py", line 221, in add_field
self._remake_table(model, create_fields=[field])
File "/home/piranha/.virtualenvs/Python_3.5-Django_1.9/lib/python3.5/site-packages/django/db/backends/sqlite3/schema.py", line 181, in _remake_table
self.create_model(temp_model)
File "/home/piranha/.virtualenvs/Python_3.5-Django_1.9/lib/python3.5/site-packages/django/db/backends/base/schema.py", line 250, in create_model
to_column = field.remote_field.model._meta.get_field(field.remote_field.field_name).column
File "/home/piranha/.virtualenvs/Python_3.5-Django_1.9/lib/python3.5/site-packages/django/db/models/options.py", line 582, in get_field
raise FieldDoesNotExist('%s has no field named %r' % (self.object_name, field_name))
django.core.exceptions.FieldDoesNotExist: Customer has no field named 'id'
Again, the problem seems to only occur when using SQLite and including the self-referencing ForeignKey. I think it is occurring because SQLite can't ALTER columns resulting in Django rebuilding the table, but the self-referencing ForeignKey is causing the rebuild to look for the 'id' column which no longer exists in the new model.
I've tried manually adjusting the migration operations every which way and even adding a migrations.RunPython with apps.get_model() to use the historical version of the model. Nothing seems to work.
How can I adjust the following migration to avoid the error:
Migration
# -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-09-07 01:16
from __future__ import unicode_literals
from django.conf import settings
import django.contrib.auth.models
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('base', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='customer',
options={'verbose_name': 'user', 'verbose_name_plural': 'users'},
),
migrations.AlterModelManagers(
name='customer',
managers=[
('objects', django.contrib.auth.models.UserManager()),
],
),
migrations.RemoveField(
model_name='customer',
name='account',
),
migrations.RemoveField(
model_name='customer',
name='id',
),
migrations.AddField(
model_name='customer',
name='user_ptr',
field=models.OneToOneField(auto_created=True, default=None, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to=settings.AUTH_USER_MODEL),
preserve_default=False,
),
]
And, yes, I know I'll ultimately need to break the migration into multiple phases and do a data migration to put something useful in the new user_ptr field.
Ok, it took me a while to work out: but basically, I don't think you can do this:
class Customer(User):
parent = models.ForeignKey('self', null=True)
Instead, it should be something more like (untested:)
class Customer(User):
parent = models.ForeignKey('admin.User', null=True)
If you want to make sure that data integrity is actually a Customer, you could put a pre-validate in save (or something, if you're using a save-pipeline of some kind)
If you include a data migration step to preserve that value as well, perhaps through using a temporary value to store it in (or dump and reinsert the objects).
I deleted my db.sqlite3 and the file on my migration folder except __init__.py but including the __pycache__ folder.
My app's models are multiple files in a folder with an __init__.py file with some import and an __all__ variable (I don't know if this matter).
From the prompt I give the first migrate command and it look to work (migrating sessions, admin, auth, registration, contenttypes. There isn't my app 'core').
So i give the first makemigrations command and again the migrate command.
This time it give an error:
ValueError: invalid literal for int() with base 10: 'basic'
In a model there's an ForeignKey fields with default='basic'. basic will be an object of the related class but actually it don't exist (before I create the database, then I will populate it). I think it's normal.
Anyway I change in default=1 and it works (but 1 will not be an object, so it's wrong!)
My model:
Class Payment(models.Model):
name = models.CharField(max_length=32)
Class ProfileUser(models.Model):
payment = models.ForeignKey(Payment, blank=True, null=True,
default='basic', on_delete=models.PROTECT)
#etc
There is a way to use 'basic'? I prefer to not use id=1 because I'm not sure to know the id that basic will have (remember that now it don't exist yet).
Btw in other models I have alike situations and they appear to works...
The Whole error:
(myvenv) c:\Python34\Scripts\possedimenti\sitopossedimenti>manage.py migrate
Operations to perform:
Apply all migrations: contenttypes, core, registration, admin, auth, sessions
Running migrations:
Rendering model states... DONE
Applying core.0001_initial...Traceback (most recent call last):
File "C:\Python34\Scripts\possedimenti\sitopossedimenti\manage.py", line 10, i
n <module>
execute_from_command_line(sys.argv)
File "c:\Python34\Scripts\possedimenti\myvenv\lib\site-packages\django\core\ma
nagement\__init__.py", line 353, in execute_from_command_line
utility.execute()
File "c:\Python34\Scripts\possedimenti\myvenv\lib\site-packages\django\core\ma
nagement\__init__.py", line 345, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "c:\Python34\Scripts\possedimenti\myvenv\lib\site-packages\django\core\ma
nagement\base.py", line 348, in run_from_argv
self.execute(*args, **cmd_options)
File "c:\Python34\Scripts\possedimenti\myvenv\lib\site-packages\django\core\ma
nagement\base.py", line 399, in execute
output = self.handle(*args, **options)
File "c:\Python34\Scripts\possedimenti\myvenv\lib\site-packages\django\core\ma
nagement\commands\migrate.py", line 200, in handle
executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial)
File "c:\Python34\Scripts\possedimenti\myvenv\lib\site-packages\django\db\migr
ations\executor.py", line 92, in migrate
self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_ini
tial)
File "c:\Python34\Scripts\possedimenti\myvenv\lib\site-packages\django\db\migr
ations\executor.py", line 121, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_
initial)
File "c:\Python34\Scripts\possedimenti\myvenv\lib\site-packages\django\db\migr
ations\executor.py", line 198, in apply_migration
state = migration.apply(state, schema_editor)
File "c:\Python34\Scripts\possedimenti\myvenv\lib\site-packages\django\db\migr
ations\migration.py", line 123, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, projec
t_state)
File "c:\Python34\Scripts\possedimenti\myvenv\lib\site-packages\django\db\migr
ations\operations\fields.py", line 62, in database_forwards
field,
File "c:\Python34\Scripts\possedimenti\myvenv\lib\site-packages\django\db\back
ends\sqlite3\schema.py", line 221, in add_field
self._remake_table(model, create_fields=[field])
File "c:\Python34\Scripts\possedimenti\myvenv\lib\site-packages\django\db\back
ends\sqlite3\schema.py", line 103, in _remake_table
self.effective_default(field)
File "c:\Python34\Scripts\possedimenti\myvenv\lib\site-packages\django\db\back
ends\base\schema.py", line 210, in effective_default
default = field.get_db_prep_save(default, self.connection)
File "c:\Python34\Scripts\possedimenti\myvenv\lib\site-packages\django\db\mode
ls\fields\related.py", line 912, in get_db_prep_save
return self.target_field.get_db_prep_save(value, connection=connection)
File "c:\Python34\Scripts\possedimenti\myvenv\lib\site-packages\django\db\mode
ls\fields\__init__.py", line 728, in get_db_prep_save
prepared=False)
File "c:\Python34\Scripts\possedimenti\myvenv\lib\site-packages\django\db\mode
ls\fields\__init__.py", line 968, in get_db_prep_value
value = self.get_prep_value(value)
File "c:\Python34\Scripts\possedimenti\myvenv\lib\site-packages\django\db\mode
ls\fields\__init__.py", line 976, in get_prep_value
return int(value)
ValueError: invalid literal for int() with base 10: 'basic'
Thank You
PS: I'm using python 3.4 Django 1.9 Windows7
In your Payment model you have not explicitly designated a primary key. So django will create one for you. It will be an integer auto increment field.
Class Payment(models.Model):
name = models.CharField(max_length=32)
Now when you define Payment as a foreign key for ProfileUser, django thinks that it should be the primary key field in Payment that ought to be used as the reference.
Class ProfileUser(models.Model):
payment = models.ForeignKey(Payment, blank=True, null=True,
default='basic', on_delete=models.PROTECT)
#etc
In order to enforce this reference, the payment field needs to be an integer. And you cannot insert 'basic' into an integer field.
One solution is to use the
ForeignKey.to_field option to explicitly refer to a different field in the Payment class.
ForeignKey.to_fieldĀ¶ The field on the related object that the relation
is to. By default, Django uses the primary key of the related object.
Thus your class would become
Class ProfileUser(models.Model):
payment = models.ForeignKey(Payment, blank=True, null=True,
default='basic', on_delete=models.PROTECT,
to_field = 'name' )
#etc
Now the payment field here becomes a CharField. Note that it would be more efficient to use an integer field as a foreign key in most cases.
Another possibility is for you to define the name field in Payment as it's primary key.
Create a function to return the id (put it before the ProfileUser defenition).
def get_basic_id():
payment = Payment.options.get(name='basic')
return payment.id
Class ProfileUser(models.Model):
payment = models.ForeignKey(Payment, blank=True, null=True,
default=get_basic_id(), on_delete=models.PROTECT)
Though if you don't know what id 'basic' will have, are you certain that it will be in the database? One way around this would be to populate the payment table using fixtures.
https://docs.djangoproject.com/en/1.9/howto/initial-data/