Django - can't delete rows when migrating backwards - django

I have a problem. I implemented a migration to create another option on my model (add the preview textchoice) and implemented a RunPython method to create rows on a table that matches my requirements. This works.
The part that doesn't work is the reverse code. I simply query and filter the instances that I want to delete and try to delete them. In doing so, I get this weird error:
Unapplying applications.0012_alter_mediatype_name...Traceback (most recent call last):
File "/usr/local/lib/python3.10/runpy.py", line 196, in _run_module_as_main
return _run_code(code, main_globals, None,
File "/usr/local/lib/python3.10/runpy.py", line 86, in _run_code
exec(code, run_globals)
File "/root/.vscode-server/extensions/ms-python.python-2022.20.2/pythonFiles/lib/python/debugpy/adapter/../../debugpy/launcher/../../debugpy/__main__.py", line 39, in <module>
cli.main()
File "/root/.vscode-server/extensions/ms-python.python-2022.20.2/pythonFiles/lib/python/debugpy/adapter/../../debugpy/launcher/../../debugpy/../debugpy/server/cli.py", line 430, in main
run()
File "/root/.vscode-server/extensions/ms-python.python-2022.20.2/pythonFiles/lib/python/debugpy/adapter/../../debugpy/launcher/../../debugpy/../debugpy/server/cli.py", line 284, in run_file
runpy.run_path(target, run_name="__main__")
File "/root/.vscode-server/extensions/ms-python.python-2022.20.2/pythonFiles/lib/python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_runpy.py", line 321, in run_path
return _run_module_code(code, init_globals, run_name,
File "/root/.vscode-server/extensions/ms-python.python-2022.20.2/pythonFiles/lib/python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_runpy.py", line 135, in _run_module_code
_run_code(code, mod_globals, init_globals,
File "/root/.vscode-server/extensions/ms-python.python-2022.20.2/pythonFiles/lib/python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_runpy.py", line 124, in _run_code
exec(code, run_globals)
File "/code/ews/manage.py", line 22, in <module>
main()
File "/code/ews/manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 440, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 414, in run_from_argv
self.execute(*args, **cmd_options)
File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 460, in execute
output = self.handle(*args, **options)
File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 98, in wrapped
res = handle_func(*args, **kwargs)
File "/usr/local/lib/python3.10/site-packages/django/core/management/commands/migrate.py", line 290, in handle
post_migrate_state = executor.migrate(
File "/usr/local/lib/python3.10/site-packages/django/db/migrations/executor.py", line 137, in migrate
state = self._migrate_all_backwards(plan, full_plan, fake=fake)
File "/usr/local/lib/python3.10/site-packages/django/db/migrations/executor.py", line 215, in _migrate_all_backwards
self.unapply_migration(states[migration], migration, fake=fake)
File "/usr/local/lib/python3.10/site-packages/django/db/migrations/executor.py", line 275, in unapply_migration
state = migration.unapply(state, schema_editor)
File "/usr/local/lib/python3.10/site-packages/django/db/migrations/migration.py", line 191, in unapply
operation.database_backwards(
File "/usr/local/lib/python3.10/site-packages/django/db/migrations/operations/special.py", line 201, in database_backwards
self.reverse_code(from_state.apps, schema_editor)
File "/code/ews/applications/migrations/0012_alter_mediatype_name.py", line 45, in reverter
).delete()
File "/usr/local/lib/python3.10/site-packages/django/db/models/query.py", line 826, in delete
collector.collect(del_query)
File "/usr/local/lib/python3.10/site-packages/django/db/models/deletion.py", line 343, in collect
field.remote_field.on_delete(self, field, sub_objs, self.using)
File "/usr/local/lib/python3.10/site-packages/django/db/models/deletion.py", line 23, in CASCADE
collector.collect(
File "/usr/local/lib/python3.10/site-packages/django/db/models/deletion.py", line 321, in collect
sub_objs = self.related_objects(related_model, [field], batch)
File "/usr/local/lib/python3.10/site-packages/django/db/models/deletion.py", line 404, in related_objects
return related_model._base_manager.using(self.using).filter(predicate)
File "/usr/local/lib/python3.10/site-packages/django/db/models/query.py", line 1071, in filter
return self._filter_or_exclude(False, args, kwargs)
File "/usr/local/lib/python3.10/site-packages/django/db/models/query.py", line 1089, in _filter_or_exclude
clone._filter_or_exclude_inplace(negate, args, kwargs)
File "/usr/local/lib/python3.10/site-packages/django/db/models/query.py", line 1096, in _filter_or_exclude_inplace
self._query.add_q(Q(*args, **kwargs))
File "/usr/local/lib/python3.10/site-packages/django/db/models/sql/query.py", line 1502, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "/usr/local/lib/python3.10/site-packages/django/db/models/sql/query.py", line 1532, in _add_q
child_clause, needed_inner = self.build_filter(
File "/usr/local/lib/python3.10/site-packages/django/db/models/sql/query.py", line 1358, in build_filter
return self._add_q(
File "/usr/local/lib/python3.10/site-packages/django/db/models/sql/query.py", line 1532, in _add_q
child_clause, needed_inner = self.build_filter(
File "/usr/local/lib/python3.10/site-packages/django/db/models/sql/query.py", line 1415, in build_filter
self.check_related_objects(join_info.final_field, value, join_info.opts)
File "/usr/local/lib/python3.10/site-packages/django/db/models/sql/query.py", line 1229, in check_related_objects
self.check_query_object_type(v, opts, field)
File "/usr/local/lib/python3.10/site-packages/django/db/models/sql/query.py", line 1203, in check_query_object_type
raise ValueError(
ValueError: Cannot query "MediaSize object (0a803f4c-f9e0-4b2d-ae2a-c02d7b9e12b6)": Must be "MediaSize" instance.
This error does not make sense. Does anyone have a clue of what it can be?
The migration code:
from django.db import migrations, models
def converter(apps, schema_editor):
AppExtension = apps.get_model("applications", "AppExtension")
MediaType = apps.get_model("applications", "MediaType")
MediaSize = apps.get_model("applications", "MediaSize")
all_extensions = AppExtension.objects.all()
media_types = []
media_sizes = []
for extension in all_extensions:
mediatype_extension = MediaType(extension=extension, name="preview")
media_types.append(mediatype_extension)
media_sizes.append(
MediaSize(
media_type=mediatype_extension,
name="intrinsic",
width=1920,
height=960,
)
)
media_sizes.append(
MediaSize(
media_type=mediatype_extension,
name="optimized",
width=960,
height=480,
)
)
MediaType.objects.bulk_create(media_types)
MediaSize.objects.bulk_create(media_sizes)
def reverter(apps, schema_editor):
MediaType = apps.get_model("applications", "MediaType")
all_extensions = AppExtension.objects.all()
MediaType.objects.filter(
name="preview",
).delete()
class Migration(migrations.Migration):
dependencies = [
("applications", "0011_alter_mediatype_name"),
]
operations = [
migrations.AlterField(
model_name="mediatype",
name="name",
field=models.CharField(
choices=[
("thumbnail", "Thumbnail"),
("icon", "Icon"),
("app-icon", "App Icon"),
("preview", "Preview"),
],
default="thumbnail",
help_text="Name of this media type",
max_length=32,
verbose_name="Name",
),
),
migrations.RunPython(converter, reverse_code=reverter),
]
My models:
class MediaType(UUIDModel):
class TypeChoices(models.TextChoices):
THUMBNAIL = "thumbnail", "Thumbnail"
ICON = "icon", "Icon"
APP_ICON = "app-icon", "App Icon"
PREVIEW = "preview", "Preview"
extension = models.ForeignKey(
AppExtension,
on_delete=models.CASCADE,
related_name="media_types",
verbose_name=_("AppExtension"),
help_text="AppExtension this MediaType belongs to",
)
name = models.CharField(
max_length=32,
verbose_name=_("Name"),
help_text=f"Name of this media type",
choices=TypeChoices.choices,
default=TypeChoices.THUMBNAIL,
)
#property
def sizes_dict(self) -> dict:
if self.sizes.exist():
return {size.name: size.get_tuple() for size in self.sizes.all()}
return {}
def __str__(self) -> str:
return f"{self.extension.name} - {self.name}"
class Meta:
constraints = [
UniqueConstraint(
fields=["extension", "name"],
name="unique_media_type_name_per_extension",
),
]
class MediaSize(UUIDModel):
class SizeChoices(models.TextChoices):
INTRINSIC = "intrinsic", "Intrinsic"
OPTIMIZED = "optimized", "Optimized"
media_type = models.ForeignKey(
MediaType,
on_delete=models.CASCADE,
verbose_name=_("Media Type"),
help_text="Media type this size reffers to",
related_name="sizes",
)
name = models.CharField(
max_length=32,
verbose_name=_("Name"),
help_text=f"Name of this media size",
choices=SizeChoices.choices,
default=SizeChoices.INTRINSIC,
)
width = models.PositiveIntegerField(
verbose_name=_("Width"),
help_text="Width of this media size",
)
height = models.PositiveIntegerField(
verbose_name=_("Height"),
help_text="Height of this media size",
)
def get_tuple(self) -> Tuple[int, int]:
return self.width, self.height
def __str__(self) -> str:
return (
f"{self.media_type.extension.name} - {self.media_type.name}"
+ f" - {self.name}: ({self.get_tuple()})"
)
class Meta:
constraints = [
UniqueConstraint(
fields=["media_type", "name"],
name="unique_media_size_name_per_media_type",
),
UniqueConstraint(
fields=["media_type", "height", "width"],
name="unique_media_size_dimensions_per_media_type",
),
]
Tried to run the exact same code to delete the rows outside the migration -> it works
Tried to stop the migration in between, get a single instance of the nested MediaSize type and delete it -> raises same error
Running the migration with and without the vscode debugger raises the same error
It is possible to update and save the instance during the migration, just the delete operation raises this error.
Update:
Separating the AlterField and RunPython operations into two different migration files, and running those files separately works. Running both at once gives the same error.

Try to just remove reverse_code. I dont think you need it since the operation doesnt need to be reverted.

Related

Django ValueError: Cannot serialize: <User: username>

When I'm trying to make migrations of my models in Django, I keep getting the same error, even after I've commented out all the changes:
(.venv) C:\Users\jezdo\venv\chat\chat_proj>python manage.py makemigrations chat
Migrations for 'chat':
chat\migrations\0002_alter_customusergroup_custom_group_name_and_more.py
- Alter field custom_group_name on customusergroup
- Alter field users on customusergroup
Traceback (most recent call last):
File "C:\Users\jezdo\.venv\chat\chat_proj\manage.py", line 22, in <module>
main()
File "C:\Users\jezdo\.venv\chat\chat_proj\manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "C:\Users\jezdo\.venv\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line
utility.execute()
File "C:\Users\jezdo\.venv\lib\site-packages\django\core\management\__init__.py", line 440, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\jezdo\.venv\lib\site-packages\django\core\management\base.py", line 402, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\jezdo\.venv\lib\site-packages\django\core\management\base.py", line 448, in execute
output = self.handle(*args, **options)
File "C:\Users\jezdo\.venv\lib\site-packages\django\core\management\base.py", line 96, in wrapped
res = handle_func(*args, **kwargs)
File "C:\Users\jezdo\.venv\lib\site-packages\django\core\management\commands\makemigrations.py", line 239, in handle
self.write_migration_files(changes)
File "C:\Users\jezdo\.venv\lib\site-packages\django\core\management\commands\makemigrations.py", line 278, in write_migration_files
migration_string = writer.as_string()
File "C:\Users\jezdo\.venv\lib\site-packages\django\db\migrations\writer.py", line 141, in as_string
operation_string, operation_imports = OperationWriter(operation).serialize()
File "C:\Users\jezdo\.venv\lib\site-packages\django\db\migrations\writer.py", line 99, in serialize
_write(arg_name, arg_value)
File "C:\Users\jezdo\.venv\lib\site-packages\django\db\migrations\writer.py", line 63, in _write
arg_string, arg_imports = MigrationWriter.serialize(_arg_value)
File "C:\Users\jezdo\.venv\lib\site-packages\django\db\migrations\writer.py", line 282, in serialize
return serializer_factory(value).serialize()
File "C:\Users\jezdo\.venv\lib\site-packages\django\db\migrations\serializer.py", line 221, in serialize
return self.serialize_deconstructed(path, args, kwargs)
File "C:\Users\jezdo\.venv\lib\site-packages\django\db\migrations\serializer.py", line 99, in serialize_deconstructed
arg_string, arg_imports = serializer_factory(arg).serialize()
File "C:\Users\jezdo\.venv\lib\site-packages\django\db\migrations\serializer.py", line 50, in serialize
item_string, item_imports = serializer_factory(item).serialize()
File "C:\Users\jezdo\.venv\lib\site-packages\django\db\migrations\serializer.py", line 50, in serialize
item_string, item_imports = serializer_factory(item).serialize()
File "C:\Users\jezdo\.venv\lib\site-packages\django\db\migrations\serializer.py", line 386, in serializer_factory
raise ValueError(
ValueError: Cannot serialize: <User: jezdo>
There are some values Django cannot serialize into migration files.
For more, see https://docs.djangoproject.com/en/4.1/topics/migrations/#migration-serializing
my model in models.py:
class CustomUserGroup(models.Model):
custom_group_name = models.CharField(max_length=50, unique=True)
users= MultiSelectField(max_length=100,choices=users_list,unique=False)
class Meta:
verbose_name_plural = 'Custom Groups'
ordering = ['custom_group_name']
def __unicode__(self):
return self.custom_group_name
I wanted to create another model similar to CustomUserGroup byt with a different "users" field:
class CustomUserGroup2(models.Model):
custom_group_name = models.CharField(max_length=50, unique=True)
users= models.ManyToManyField(User)
class Meta:
verbose_name_plural = 'Custom Groups'
ordering = ['custom_group_name']
def __unicode__(self):
return self.custom_group_name
but couldn't makemigrations due to the described error. Now I cannot make any migrations whatsoever, even after having deleted the CustomUserGroup2 class.
I'm using Python 3.10.4 and Django 4.1.6.

ValueError: badly formed hexadecimal UUID string

In my system I'm trying to auto generate a unique random string for each users to be passed later on in the URL as the reference to that account and I recently read about the UUID in django models. And this is how my model looks like:
class User(AbstractBaseUser, PermissionsMixin):
card_number = models.CharField(max_length=20, unique=True)
first_name = models.CharField(max_length=150)
middle_name = models.CharField(max_length=150)
last_name = models.CharField(max_length=150)
address = models.CharField(max_length=200)
account_code = models.UUIDField(max_length=200, default=uuid.uuid4(), editable=False)
And I ran into an error when start creating superuser in the terminal:
Traceback (most recent call last):
File "C:\Users\User\PycharmProjects\ViajeroProject\viaje\manage.py", line 22, in <module>
main()
File "C:\Users\User\PycharmProjects\ViajeroProject\viaje\manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "C:\Users\User\PycharmProjects\ViajeroProject\venv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line
utility.execute()
File "C:\Users\User\PycharmProjects\ViajeroProject\venv\lib\site-packages\django\core\management\__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\User\PycharmProjects\ViajeroProject\venv\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\User\PycharmProjects\ViajeroProject\venv\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 79, in execute
return super().execute(*args, **options)
File "C:\Users\User\PycharmProjects\ViajeroProject\venv\lib\site-packages\django\core\management\base.py", line 371, in execute
output = self.handle(*args, **options)
File "C:\Users\User\PycharmProjects\ViajeroProject\venv\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 113, in handle
error_msg = self._validate_username(username, verbose_field_name, database)
File "C:\Users\User\PycharmProjects\ViajeroProject\venv\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 234, in _validate_username
self.UserModel._default_manager.db_manager(database).get_by_natural_key(username)
File "C:\Users\User\PycharmProjects\ViajeroProject\venv\lib\site-packages\django\contrib\auth\base_user.py", line 45, in get_by_natural_key
return self.get(**{self.model.USERNAME_FIELD: username})
File "C:\Users\User\PycharmProjects\ViajeroProject\venv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\User\PycharmProjects\ViajeroProject\venv\lib\site-packages\django\db\models\query.py", line 425, in get
num = len(clone)
File "C:\Users\User\PycharmProjects\ViajeroProject\venv\lib\site-packages\django\db\models\query.py", line 269, in __len__
self._fetch_all()
File "C:\Users\User\PycharmProjects\ViajeroProject\venv\lib\site-packages\django\db\models\query.py", line 1308, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "C:\Users\User\PycharmProjects\ViajeroProject\venv\lib\site-packages\django\db\models\query.py", line 70, in __iter__
for row in compiler.results_iter(results):
File "C:\Users\User\PycharmProjects\ViajeroProject\venv\lib\site-packages\django\db\models\sql\compiler.py", line 1100, in apply_converters
value = converter(value, expression, connection)
File "C:\Users\User\PycharmProjects\ViajeroProject\venv\lib\site-packages\django\db\backends\sqlite3\operations.py", line 318, in convert_uuidfield_value
value = uuid.UUID(value)
File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\uuid.py", line 177, in __init__
raise ValueError('badly formed hexadecimal UUID string')
ValueError: badly formed hexadecimal UUID string
How should I address this or is this practice not advisable where I auto generate a unique random string as reference for the user in the URL? Note that users still have their PKs which different from the account_code.
Thank you!
You need to import the module and use default=uuid.uuid4 instead of default=uuid.uuid4()

ValueError: Field 'id' expected a number but got 'DEFAULT VALUE'

When I try to execute python manage.py migrate I get this error: ValueError: Field 'id' expected a number but got 'DEFAULT VALUE'.What could be wrong with my code.Any help pleaseThanks in advance.
File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 1772, in get_prep_value
return int(value)
ValueError: invalid literal for int() with base 10: 'DEFAULT VALUE'
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/risper/django_projects/env01/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
utility.execute()
File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/core/management/base.py", line 328, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/core/management/base.py", line 369, in execute
output = self.handle(*args, **options)
File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped
res = handle_func(*args, **kwargs)
File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 233, in handle
fake_initial=fake_initial,
File "/home/risper/django_projects/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/risper/django_projects/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/risper/django_projects/env01/lib/python3.6/site-packages/django/db/migrations/executor.py", line 245, in apply_migration
state = migration.apply(state, schema_editor)
File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/db/migrations/migration.py", line 124, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/db/migrations/operations/fields.py", line 112, in database_forwards
field,
File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/db/backends/sqlite3/schema.py", line 328, in add_field
self._remake_table(model, create_field=field)
File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/db/backends/sqlite3/schema.py", line 189, in _remake_table
self.effective_default(create_field)
File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 303, in effective_default
return field.get_db_prep_save(self._effective_default(field), self.connection)
File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/db/models/fields/related.py", line 939, in get_db_prep_save
return self.target_field.get_db_prep_save(value, connection=connection)
File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 821, in get_db_prep_save
return self.get_db_prep_value(value, connection=connection, prepared=False)
File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 2365, in get_db_prep_value
value = self.get_prep_value(value)
File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 1776, in get_prep_value
) from e
ValueError: Field 'id' expected a number but got 'DEFAULT VALUE'.
Here is my models py file where I have defined my models:
from django.db import models
# Create your models here.
class ImageModel(models.Model):
imagefile=models.ImageField(upload_to='images', null=True, verbose_name="")
def __str__(self):
return str(self.imagefile)
class Diseases(models.Model):
disease_name=models.CharField(max_length=100)
description=models.CharField(max_length=100)
def __str__(self):
return self.disease_name
class Pestisides(models.Model):
pestiside_name=models.CharField(max_length=100)
directions=models.CharField(max_length=100)
price=models.CharField(max_length=100)
#test_location=
#time
disease= models.ManyToManyField(Disease)
def __str__(self):
return self.pestiside_name
class Predictions(models.Model):
#user= models.ForeignKey(User, on_delete=models.CASCADE,null=True)
disease = models.ForeignKey(Diseases,on_delete=models.CASCADE)
Here is my admin py file where I have registered my models:
from django.contrib import admin
from .models import *
# Register your models here.
admin.site.register(ImageModel)
admin.site.register(Diseases)
admin.site.register(Pestisides)
admin.site.register(Predictions)
Firstly disease = models.ManyToManyField(Diseases) correct model Name. Then delete all your migrations and then type manage.py makemigrations and migrate commands. I hope it will work
class Pestisides(models.Model):
pestiside_name = models.CharField(max_length=100)
directions = models.CharField(max_length=100)
price = models.CharField(max_length=100)
# test_location=
# time
disease = models.ManyToManyField(Diseases)

Django: Trying to make Users migration with a self-referential default value

I'm trying to set a default value on a field I added to my User model, but I'm having to do a lot of acrobativs to make it work.
I want to add an 'identifier' SlugField with a default value defined in a function, like so:
def create_identifier():
while True:
identifier = ''.join(random.SystemRandom().choice('23456789BCDFGHJKMNPQRSTVWXYZ') for _ in range(15))
if not User.objects.filter(identifier=identifier).exists():
return identifier
class User(AbstractUser):
identifier = models.SlugField(default=create_identifier, max_length=16)
def __str__(self):
return self.username
This exact scenario works fine on a different (not User) nodel class, but when I try to run migrations with this code for User, I get:
Traceback (most recent call last):
File "manage.py", line 29, in <module>
execute_from_command_line(sys.argv)
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
utility.execute()
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/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/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/core/management/base.py", line 332, in execute
self.check()
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/core/management/base.py", line 364, in check
include_deployment_checks=include_deployment_checks,
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 58, in _run_checks
issues.extend(super()._run_checks(**kwargs))
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/core/management/base.py", line 351, in _run_checks
return checks.run_checks(**kwargs)
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/core/checks/registry.py", line 73, in run_checks
new_errors = check(app_configs=app_configs)
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/contrib/auth/checks.py", line 74, in check_user_model
if isinstance(cls().is_anonymous, MethodType):
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/db/models/base.py", line 469, in __init__
val = field.get_default()
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 775, in get_default
return self._get_default()
File "/home/myprojectname/myprojectname/myprojectname/users/models.py", line 34, in create_identifier
if not User.objects.filter(identifier=identifier).exists():
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/db/models/query.py", line 715, in exists
return self.query.has_results(using=self.db)
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/db/models/sql/query.py", line 509, in has_results
return compiler.has_results()
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1037, in has_results
return bool(self.execute_sql(SINGLE))
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1068, in execute_sql
cursor.execute(sql, params)
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/db/backends/utils.py", line 100, in execute
return super().execute(sql, params)
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/db/backends/utils.py", line 68, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/db/utils.py", line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "users_user" does not exist
LINE 1: SELECT (1) AS "a" FROM "users_user" WHERE "users_user"."iden...
I have to manually modify the migrations as such:
migrations.CreateModel(
name='User',
fields=[
...
('identifier', models.SlugField(default='', max_length=16)),
...
),
migrations.AlterField(
model_name='user',
name='identifier',
field=models.SlugField(default=myprojectname.users.models.create_identifier, max_length=16),
),
And then if I initially set default='' in the models.py and run migrations it works, and I can change back to default=create_identifier after the fact.
class User(AbstractUser):
identifier = models.SlugField(default='', max_length=16)
def __str__(self):
return self.username
Is there any way I can make this work without having to go through these measures?
Edit: Would I be better off just leaving blank=True, null=True and overriding the model's save() method to change the value if the field is blank or null?
I seem to have solved the issue by modifying create_identifier to the following:
def create_identifier():
while True:
identifier = ''.join(random.SystemRandom().choice('23456789BCDFGHJKMNPQRSTVWXYZ') for _ in range(15))
try:
present = User.objects.first()
except:
present = None
if present:
if not User.objects.filter(identifier=identifier).exists():
return identifier
else:
return identifier

Fail Load Data Fixtures Django - integer out of range

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.