This is what my models.py looks like:
from django.db import models
from django.core.validators import RegexValidator
# Create your models here.
class Customer(models.Model):
customer_id = models.AutoField(primary_key=True,unique=True)
full_name = models.CharField(max_length=50)
user_email = models.EmailField(max_length=50)
user_pass = models.CharField(max_length=30)
def __str__(self):
return "%s" % self.full_name
class CustomerDetail(models.Model):
phone_regex = RegexValidator(regex = r'^\d{10}$', message = "Invalid format! E.g. 4088385778")
date_regex = RegexValidator(regex = r'\d{2}[-/]\d{2}[-/]\d{2}', message = "Invalid format! E.g. 05/16/91")
address = models.CharField(max_length=100)
date_of_birth = models.CharField(validators = [date_regex], max_length = 10, blank = True)
company = models.CharField(max_length=30)
home_phone = models.CharField(validators = [phone_regex], max_length = 10, blank = True)
work_phone = models.CharField(validators = [phone_regex], max_length = 10, blank = True)
customer_id = models.ForeignKey(Customer, on_delete=models.CASCADE)
I added customer_id to Customer after I added the same in CustomerDetail as foreign key. Why do I still get this error after running migrate, even after I added unique=True to customer_id?
Error:
Rendering model states... DONE
Applying newuser.0003_auto_20160823_0128...Traceback (most recent call last):
File "/home/krag91/Documents/djangodev/virtualenv /lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/home/krag91/Documents/djangodev/virtualenv /lib/python3.5/site-packages/django/db/backends/sqlite3/base.py", line 337, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.IntegrityError: UNIQUE constraint failed: newuser_customer.customer_id
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 "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute()
File "/home/krag91/Documents/djangodev/virtualenv/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/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/core/management/base.py", line 305, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/core/management/base.py", line 356, in execute
output = self.handle(*args, **options)
File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/core/management/commands/migrate.py", line 202, in handle
targets, plan, fake=fake, fake_initial=fake_initial
File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/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 "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/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 "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/db/migrations/executor.py", line 237, in apply_migration
state = migration.apply(state, schema_editor)
File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/db/migrations/migration.py", line 129, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/db/migrations/operations/fields.py", line 84, in database_forwards
field,
File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/db/backends/sqlite3/schema.py", line 231, in add_field
self._remake_table(model, create_fields=[field])
File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/db/backends/sqlite3/schema.py", line 199, in _remake_table
self.quote_name(model._meta.db_table),
File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/db/backends/base/schema.py", line 112, in execute
cursor.execute(sql, params)
File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/db/backends/utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/db/utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/db/backends/sqlite3/base.py", line 337, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: UNIQUE constraint failed: newuser_customer.customer_id
It seems like you are already having some objects as per old model definitions. By default django creates a field named as id to every model in database. It can be accesses by modelName.id.
In your case I guess what happened is that you are having some objects in database with customer.id as primary as primary key. So when you changed the models and applied migrations, existing objects are checked and another unique field is tried to added as a primary key. Here the workaround is to delete all the existing objects after removing the customer_id field and then try recreating the field and run migrations.
HTH
Related
I added a custom extension to djangos User model and now I'm getting this error on my localhost url:
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: column users_account.birthday does not exist
LINE 1: ... "users_account"."id", "users_account"."user_id", "users_acc...
^
Furthermore, when I tried to migrate my changes I got this error in the terminal:
Operations to perform:
Apply all migrations: admin, auth, chaburah, contenttypes, sessions, taggit, users
Running migrations:
Applying users.0002_alter_account_birthday...Traceback (most recent call last):
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/db/backends/utils.py", line 89, in _execute
return self.cursor.execute(sql, params)
psycopg2.errors.UndefinedColumn: column "birthday" does not exist
LINE 1: ..._account" ALTER COLUMN "birthday" TYPE date USING "birthday"...
^
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/almoni/Desktop/Code/my_chaburah/manage.py", line 22, in <module>
main()
File "/Users/almoni/Desktop/Code/my_chaburah/manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line
utility.execute()
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/core/management/__init__.py", line 440, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/core/management/base.py", line 414, in run_from_argv
self.execute(*args, **cmd_options)
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/core/management/base.py", line 460, in execute
output = self.handle(*args, **options)
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/core/management/base.py", line 98, in wrapped
res = handle_func(*args, **kwargs)
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/core/management/commands/migrate.py", line 290, in handle
post_migrate_state = executor.migrate(
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/db/migrations/executor.py", line 131, in migrate
state = self._migrate_all_forwards(
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/db/migrations/executor.py", line 163, in _migrate_all_forwards
state = self.apply_migration(
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/db/migrations/executor.py", line 248, in apply_migration
state = migration.apply(state, schema_editor)
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/db/migrations/migration.py", line 131, in apply
operation.database_forwards(
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/db/migrations/operations/fields.py", line 235, in database_forwards
schema_editor.alter_field(from_model, from_field, to_field)
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/db/backends/base/schema.py", line 747, in alter_field
self._alter_field(
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/db/backends/postgresql/schema.py", line 231, in _alter_field
super()._alter_field(
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/db/backends/base/schema.py", line 963, in _alter_field
self.execute(
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/db/backends/base/schema.py", line 192, in execute
cursor.execute(sql, params)
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/db/backends/utils.py", line 103, in execute
return super().execute(sql, params)
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/db/backends/utils.py", line 67, in execute
return self._execute_with_wrappers(
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/db/backends/utils.py", line 80, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/db/backends/utils.py", line 89, in _execute
return self.cursor.execute(sql, params)
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/db/utils.py", line 91, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/db/backends/utils.py", line 89, in _execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: column "birthday" does not exist
LINE 1: ..._account" ALTER COLUMN "birthday" TYPE date USING "birthday"...
It only appears when I try to either edit an existing User or create a new one.
models.py:
class Account(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
birthday = models.DateTimeField(blank=True, null=True)
def __str__(self):
return self.user
admin.py:
class AccountInline(admin.StackedInline):
model = Account
can_delete = False
verbose_name_plural = 'Accounts'
class CustomUserAdmin(UserAdmin):
inlines = (AccountInline,)
admin.site.unregister(User)
admin.site.register(User, CustomUserAdmin)
My original guess was the error was due to the fact that my existing Users have no birthday but that doesn't explain why I can't create a new User. Which makes me think I am unaware of what the actual problem is.
I'm newish to django/SQl so I don't really understand the error itself.
You forgot about:
python manage.py makemigrations
# and/or
python manage.py migrate
If error still occurs - delete the database, create new and then run above commands. If got still same error - delete the database and all migration files and then run the commands.
PS You probably want DateField not DateTimeField for birthday storage :)
I moved these to models to chat app
class Message(models.Model):
sender = models.ForeignKey(CustomUser, on_delete=models.CASCADE, verbose_name="فرستنده")
receiver = models.ForeignKey(CustomUser, on_delete=models.CASCADE, verbose_name="گیرنده", related_name="reciver")
text = models.CharField("متن", max_length=500)
date_and_time = models.DateTimeField(auto_now_add=True)
subject=models.CharField(max_length=200,verbose_name="موضوع")
notification=models.OneToOneField(Notification,on_delete=models.DO_NOTHING,related_name="message",null=True)
class Meta:
verbose_name = "پیام"
verbose_name_plural = "پیام ها"
class Response(Message):
darkhast_sabt_sherekat = models.ForeignKey(SabteSherkat,on_delete=models.CASCADE,related_name="responses")
After that, it raise an error saying the local id of Response crashed with message I made everything undo and this error keeps coming up
*
Operations to perform:
Apply all migrations: accounts, admin, auth, consultation, contenttypes, sessions, utilities, web
Running migrations:
Applying web.0007_auto_20210815_0831...Traceback (most recent call last):
File "/home/hamed/sqh-source/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 86, in _execute
return self.cursor.execute(sql, params)
File "/home/hamed/sqh-source/venv/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 396, in execute
return Database.Cursor.execute(self, query, params)
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 21, in <module>
main()
File "manage.py", line 17, in main
execute_from_command_line(sys.argv)
File "/home/hamed/sqh-source/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
utility.execute()
File "/home/hamed/sqh-source/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/hamed/sqh-source/venv/lib/python3.8/site-packages/django/core/management/base.py", line 328, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/hamed/sqh-source/venv/lib/python3.8/site-packages/django/core/management/base.py", line 369, in execute
output = self.handle(*args, **options)
File "/home/hamed/sqh-source/venv/lib/python3.8/site-packages/django/core/management/base.py", line 83, in wrapped
res = handle_func(*args, **kwargs)
File "/home/hamed/sqh-source/venv/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 231, in handle
post_migrate_state = executor.migrate(
File "/home/hamed/sqh-source/venv/lib/python3.8/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/hamed/sqh-source/venv/lib/python3.8/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/hamed/sqh-source/venv/lib/python3.8/site-packages/django/db/migrations/executor.py", line 245, in apply_migration
state = migration.apply(state, schema_editor)
File "/home/hamed/sqh-source/venv/lib/python3.8/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/hamed/sqh-source/venv/lib/python3.8/site-packages/django/db/migrations/operations/fields.py", line 178, in database_forwards
schema_editor.remove_field(from_model, from_model._meta.get_field(self.name))
File "/home/hamed/sqh-source/venv/lib/python3.8/site-packages/django/db/backends/sqlite3/schema.py", line 346, in remove_field
self._remake_table(model, delete_field=field)
File "/home/hamed/sqh-source/venv/lib/python3.8/site-packages/django/db/backends/sqlite3/schema.py", line 283, in _remake_table
self.execute("INSERT INTO %s (%s) SELECT %s FROM %s" % (
File "/home/hamed/sqh-source/venv/lib/python3.8/site-packages/django/db/backends/base/schema.py", line 142, in execute
cursor.execute(sql, params)
File "/home/hamed/sqh-source/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 100, in execute
return super().execute(sql, params)
File "/home/hamed/sqh-source/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 68, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/home/hamed/sqh-source/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/home/hamed/sqh-source/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 86, in _execute
return self.cursor.execute(sql, params)
File "/home/hamed/sqh-source/venv/lib/python3.8/site-packages/django/db/utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/home/hamed/sqh-source/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 86, in _execute
return self.cursor.execute(sql, params)
File "/home/hamed/sqh-source/venv/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 396, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: near ")": syntax error
*
I deleted every pycache and my DB and even my virtualenv but this error keeps coming up!!!!
Add abstract = True in Message models Meta class, maybe that's the issue.
class Message(models.Model):
class Meta:
verbose_name = "پیام"
verbose_name_plural = "پیام ها"
abstract = True
When I tried to migrate my project to a different version I faced this error:
ProgrammingError: ERROR: the id column specified in the foreign key constraint does not exist.
UPDATE: This is the full log: The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 23, in <module>
execute_from_command_line(sys.argv)
File "/home/user/MyProjects/forest-venv/lib/python3.5/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
utility.execute()
File "/home/user/MyProjects/forest-venv/lib/python3.5/site-packages/django/core/management/__init__.py", line 365, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/user/MyProjects/forest-venv/lib/python3.5/site-packages/django/core/management/base.py", line 288, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/user/MyProjects/forest-venv/lib/python3.5/site-packages/django/core/management/base.py", line 335, in execute
output = self.handle(*args, **options)
File "/home/user/MyProjects/forest-venv/lib/python3.5/site-packages/django/core/management/commands/migrate.py", line 200, in handle
fake_initial=fake_initial,
File "/home/user/MyProjects/forest-venv/lib/python3.5/site-packages/django/db/migrations/executor.py", line 117, in migrate
state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
File "/home/user/MyProjects/forest-venv/lib/python3.5/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
File "/home/user/MyProjects/forest-venv/lib/python3.5/site-packages/django/db/migrations/executor.py", line 244, in apply_migration
state = migration.apply(state, schema_editor)
File "/home/user/MyProjects/forest-venv/lib/python3.5/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/user/MyProjects/forest-venv/lib/python3.5/site-packages/django/db/migrations/operations/fields.py", line 216, in database_forwards
schema_editor.alter_field(from_model, from_field, to_field)
File "/home/user/MyProjects/forest-venv/lib/python3.5/site-packages/django/db/backends/base/schema.py", line 525, in alter_field
old_db_params, new_db_params, strict)
File "/home/user/MyProjects/forest-venv/lib/python3.5/site-packages/django/db/backends/postgresql/schema.py", line 122, in _alter_field
new_db_params, strict,
File "/home/user/MyProjects/forest-venv/lib/python3.5/site-packages/django/db/backends/base/schema.py", line 750, in _alter_field
self.execute(self._create_fk_sql(model, new_field, "_fk_%(to_table)s_%(to_column)s"))
File "/home/user/MyProjects/forest-venv/lib/python3.5/site-packages/django/db/backends/base/schema.py", line 133, in execute
cursor.execute(sql, params)
File "/home/user/MyProjects/forest-venv/lib/python3.5/site-packages/django/db/backends/utils.py", line 100, in execute
return super().execute(sql, params)
File "/home/user/MyProjects/forest-venv/lib/python3.5/site-packages/django/db/backends/utils.py", line 68, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/home/user/MyProjects/forest-venv/lib/python3.5/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/home/user/MyProjects/forest-venv/lib/python3.5/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "/home/user/MyProjects/forest-venv/lib/python3.5/site-packages/django/db/utils.py", line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/home/user/MyProjects/forest-venv/lib/python3.5/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
But I don't have an id column in my model:
from django.db import models
from django.utils.translation import ugettext_lazy as _
from renter.models import RefAbstract, Renter
from django.contrib.gis.db import models
from textwrap import shorten
class Unitt(RefAbstract):
....//some classes
class Task(RefAbstract):
class Meta(RefAbstract.Meta):
verbose_name = 'task'
verbose_name_plural = 'tasks'
class Spatial(models.Model):
codeq = models.IntegerField('no',help_text='no')
code = models.PositiveIntegerField('cutare',primary_key=True,help_text='cutare')//unique column
codeV = models.IntegerField('novi',help_text='novi')
renter = models.ForeignKey(Renter, on_delete=models.DO_NOTHING, verbose_name='renter')
geometry = models.MultiPolygonField(geography=True, verbose_name='geometry')
class Meta:
verbose_name = 'cutarea'
verbose_name_plural = 'cutarea'
class LScharacteristic(models.Model):
codels = models.ForeignKey(Spatial, on_delete=models.DO_NOTHING, verbose_name = 'cutarea')// Foreign Key
tract = models.CharField('tract',max_length = 80, help_text='tract')
task = models.ForeignKey(Task, on_delete=models.DO_NOTHING, verbose_name='task')
totalarea = models.PositiveIntegerField('totarea',help_text = 'totarea')
explarea = models.PositiveIntegerField('exarea',help_text = 'exarea')
protecttype = models.CharField('category',max_length = 50, help_text = 'category')
class Meta:
verbose_name = 'characteristic'
verbose_name_plural = 'characteristics'
class PlannedUsing(models.Model):
codels = models.ForeignKey(Spatial, on_delete=models.DO_NOTHING, verbose_name = 'cutarea') // Foreign Key
codeq = models.IntegerField(help_text='number')
cutareaShape = models.ForeignKey(CutareaShape, on_delete=models.DO_NOTHING, verbose_name='form')
cuttype = models.ForeignKey(CutareaType, on_delete=models.DO_NOTHING, verbose_name='type1')
managetype = models.ForeignKey(ManageType, on_delete=models.DO_NOTHING, verbose_name='type2')
unit = models.ForeignKey(Unitt, on_delete=models.DO_NOTHING, verbose_name='unit')
composition = models.ForeignKey(Composition, on_delete=models.DO_NOTHING, verbose_name='sort')
assortment = models.ForeignKey(Assortment, on_delete=models.DO_NOTHING, verbose_name='assort')
class Meta:
verbose_name = 'planus'
verbose_name_plural = 'planuss'
What is the id column and why does it exist if I never defined it?
How I can to fix this?
I think that the problem is that your ForeignKey fields do not point explicitly to the field that you have marked as primary (Spatial.code).
By marking Spatial.code as primary you prevent Django from creating the id field. See the documentation But if you point a ForeignKey to just a model it will try to link to the id field of that model.
To fix this you can add to your ForeignKey field the parameter: to_field='code' and add unique=True to Spatial.code.See documentation
You can use
def __str__(self):
return self.etat
or
def __int__(self):
For specif what do you return on your django model.
like this:
tests= models.CharField(max_length=100, verbose_name="Test")
class Meta:
verbose_name = "Tests"
ordering = ['tests']
def __str__(self):
return self.tests
I migrated to sqlite3 to postgresql database and i tried to migrate but it will always throw a exception I am also using drf.
Here is my output:
Operations to perform:
Apply all migrations: admin, auth, authtoken, contenttypes, sessions
Running migrations:
Applying contenttypes.0002_remove_content_type_name...Traceback (most recent call last):
File "/home/dawid/django/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
psycopg2.ProgrammingError: column "name" of relation "django_content_type" does not exist
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 "/home/dawid/django/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line
utility.execute()
File "/home/dawid/django/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 355, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/dawid/django/venv/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/dawid/django/venv/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute
output = self.handle(*args, **options)
File "/home/dawid/django/venv/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 204, in handle
fake_initial=fake_initial,
File "/home/dawid/django/venv/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/dawid/django/venv/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/dawid/django/venv/lib/python3.6/site-packages/django/db/migrations/executor.py", line 244, in apply_migration
state = migration.apply(state, schema_editor)
File "/home/dawid/django/venv/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/dawid/django/venv/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/dawid/django/venv/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 515, in alter_field
old_db_params, new_db_params, strict)
File "/home/dawid/django/venv/lib/python3.6/site-packages/django/db/backends/postgresql/schema.py", line 112, in _alter_field
new_db_params, strict,
File "/home/dawid/django/venv/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 684, in _alter_field
params,
File "/home/dawid/django/venv/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 120, in execute
cursor.execute(sql, params)
File "/home/dawid/django/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 80, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/home/dawid/django/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "/home/dawid/django/venv/lib/python3.6/site-packages/django/db/utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/home/dawid/django/venv/lib/python3.6/site-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/home/dawid/django/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: column "name" of relation "django_content_type" does not exist
My Bucketlist model has the following code:
class Bucketlist(models.Model):
"""This class represents the bucketlist model."""
name = models.CharField(max_length=255, blank=False, unique=True)
owner = models.ForeignKey(
'auth.User',
related_name='bucketlists',
on_delete=models.CASCADE)
date_created = models.DateTimeField(auto_now_add=True)
date_modified = models.DateTimeField(auto_now=True)
def __str__(self):
"""Return a human readable representation of the model instance."""
return "{}".format(self.name)
# This receiver handles token creation when a new user is created.
#receiver(post_save, sender=User)`enter code here`
def create_auth_token(sender, instance=None, created=False, **kwargs):
if created:
Token.objects.create(user=instance)
You can try these solutions,
Either you dump/flush your database if you can afford to. And then try to migrate to PostgreSQL.
Follow these steps:
Dump your database to JSON.
./manage.py dumpdata --natural-primary --natural-foreign > data.json
Change the settings for default database in settings.py i.e. switch to PostgreSQL.
Sync the database.
./manage.py migrate
Load the data that you stored in data.json
./manage.py loaddata data.json
I'm developing app using Django and Postgre.
Basically, I create new model on my app.
from django.db import models
from manager.models.state import State
from django.contrib.auth.models import User
class Address (models.Model):
address_id = models.AutoField(primary_key=True)
address_name = models.CharField(max_length=500)
address_city = models.CharField(max_length=250)
address_phone = models.IntegerField()
address_postcode = models.CharField(max_length=10, default = 0)
state = models.ForeignKey(State, null=True, blank=True, default = None)
user = models.ForeignKey(User, null=True, blank=True, default = None)
def __unicode__(self):
return self.address_id
#classmethod
def get_list(cls):
return list(cls.objects.values())
After that I run makemigrations and migrate commandline. All of the models are created on database normally.
I successfully load data from other json file (fixtures).
When I tried to loaddata address.json on Address table, I got this error.
The Error Message:
django.db.utils.DataError: Problem installing fixture '/Users/eeldwin/Documents/Django/fbt/manager/fixtures/address.json': Could not load manager.Address(pk=1): integer out of range
The Traceback:
Traceback (most recent call last):
File "manage.py", line 11, in <module>
execute_from_command_line(sys.argv)
File "/Users/eeldwin/.virtualenvs/fbt/lib/python2.7/site-packages/django /core/management/__init__.py", line 385, in execute_from_command_line
utility.execute()
File "/Users/eeldwin/.virtualenvs/fbt/lib/python2.7/site-packages/django/core/management/__init__.py", line 377, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/eeldwin/.virtualenvs/fbt/lib/python2.7/site-packages/django/core/management/base.py", line 288, in run_from_argv
self.execute(*args, **options.__dict__)
File "/Users/eeldwin/.virtualenvs/fbt/lib/python2.7/site-packages/django/core/management/base.py", line 338, in execute
output = self.handle(*args, **options)
File "/Users/eeldwin/.virtualenvs/fbt/lib/python2.7/site-packages/django/core/management/commands/loaddata.py", line 61, in handle
self.loaddata(fixture_labels)
File "/Users/eeldwin/.virtualenvs/fbt/lib/python2.7/site-packages/django/core/management/commands/loaddata.py", line 91, in loaddata
self.load_label(fixture_label)
File "/Users/eeldwin/.virtualenvs/fbt/lib/python2.7/site-packages/django/core/management/commands/loaddata.py", line 148, in load_label
obj.save(using=self.using)
File "/Users/eeldwin/.virtualenvs/fbt/lib/python2.7/site-packages/django/core/serializers/base.py", line 173, in save
models.Model.save_base(self.object, using=using, raw=True)
File "/Users/eeldwin/.virtualenvs/fbt/lib/python2.7/site-packages/django/db/models/base.py", line 617, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/Users/eeldwin/.virtualenvs/fbt/lib/python2.7/site-packages/django/db/models/base.py", line 679, in _save_table
forced_update)
File "/Users/eeldwin/.virtualenvs/fbt/lib/python2.7/site-packages/django/db/models/base.py", line 723, in _do_update
return filtered._update(values) > 0
File "/Users/eeldwin/.virtualenvs/fbt/lib/python2.7/site-packages/django/db/models/query.py", line 600, in _update
return query.get_compiler(self.db).execute_sql(CURSOR)
File "/Users/eeldwin/.virtualenvs/fbt/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 1004, in execute_sql
cursor = super(SQLUpdateCompiler, self).execute_sql(result_type)
File "/Users/eeldwin/.virtualenvs/fbt/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 786, in execute_sql
cursor.execute(sql, params)
File "/Users/eeldwin/.virtualenvs/fbt/lib/python2.7/site-packages/django/db/backends/utils.py", line 81, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/Users/eeldwin/.virtualenvs/fbt/lib/python2.7/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "/Users/eeldwin/.virtualenvs/fbt/lib/python2.7/site-packages/django/db/utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/Users/eeldwin/.virtualenvs/fbt/lib/python2.7/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
django.db.utils.DataError: Problem installing fixture '/Users/eeldwin/Documents/Django/fbt/manager/fixtures/address.json': Could not load manager.Address(pk=1): integer out of range
Here's my fixtures
[{
"model": "manager.address",
"pk": 1,
"fields": {
"address_id": "1",
"address_name": "Jalan Muara Mas Timur 242",
"address_city": "Semarang",
"address_phone": "087832270893",
"address_postcode": "3122",
"state": "1"
}}]
However, when I inserted data to database manually, it will run perfectly. Any ideas what's happened here? Thanks.
You store address_phone as IntegerField. Its max value is 2147483647 (https://docs.djangoproject.com/en/1.7/ref/models/fields/#integerfield).
But in your fixtures you try to add 087832270893 as address_phone, that why you receive integer out of range error.