2

I have been trying to do this data migration and i keep getting this error django.db.utils.DataError: value too long for type character varying(1)

My goal is to add a row to the User table here is the migration file I have written, but I cannot find the model that has a max_length of 1

# Generated by Django 2.2.7 on 2019-12-13 14:52

from django.db import migrations



class Migration(migrations.Migration):

    dependencies = [
        ('shared', '0001_initial'),
    ]

    def doit(apps, schema_editor):
        Tuser = apps.get_model('shared', 'User')
        nice = Tuser(user_id=True, first_name='Tom', last_name='Beals', membership= 'Di')
        nice.save()


    operations = [
        migrations.RunPython(doit),
    ]

here is my models.py file. (the model I referencing is the last one)

from django.db import models

# Create your models here.
class Games(models.Model):

    game_id=models.AutoField(primary_key=True)
    game_name=models.CharField(max_length=15)
    game_odds=models.DecimalField(max_digits=5, decimal_places=2)

class GameAccount(models.Model):

    game_account_id=models.AutoField(primary_key=True)

class Deck(models.Model):
    image = models.ImageField(upload_to='images/deckOfCards/')
    suit = models.CharField(max_length=30)
    rank = models.CharField(max_length=30)
    worth = models.IntegerField()



class Dice(models.Model):
    image = models.ImageField(upload_to='images/dieFace/')
    side = models.IntegerField
class Rooms(models.Model):

    BED_CHOICES=[
        ('S', 'Single'),
        ('D', 'Double'),
        ('Q', 'Queen'),
        ('K', 'King'),
    ]
    FLOOR_CHOICES = [
        ('1', 'First'),
        ('2', 'Second'),
        ('3', 'Third'),
        ('4', 'Fourth'),
    ]

    room_num=models.AutoField(primary_key=True)
    room_price=models.DecimalField(max_digits=5, decimal_places=2)
    room_bed=models.CharField(max_length=30, choices=BED_CHOICES)
    room_floor=models.CharField(max_length=30, choices=FLOOR_CHOICES)
class UserAuth(models.Model):

    user_auth_id=models.AutoField(primary_key=True)
    user_username=models.CharField(max_length=30)
    user_pass=models.CharField(max_length=12)


class UserHistory(models.Model):

    user_history_id=models.AutoField(primary_key=True)
    previous_account_balance=models.DecimalField(max_digits=5, decimal_places=2)
    average_user_stay=models.DateTimeField()

class UserAccount(models.Model):

    user_account_id=models.AutoField(primary_key=True)
    user_account_alias=models.CharField(max_length=30)
    user_account_balance=models.DecimalField(max_digits=5, decimal_places=2)
    user_account_image=models.ImageField(upload_to='images/userAccountImage/')

class UserResortConfig(models.Model):

    user_resort_config_id=models.AutoField(primary_key=True)
    is_return_user=models.BooleanField()

class UserResortData(models.Model):

    user_resort_data_id=models.AutoField(primary_key=True)
    is_resort_guest=models.BooleanField()
    length=models.IntegerField()
    start_date=models.DateTimeField()
    end_date=models.DateTimeField()
    is_extended=models.BooleanField()
    extended_start_date=models.DateTimeField()
    extended_end_date=models.DateTimeField()

class UserGamingData(models.Model):

    user_gaming_data_id=models.AutoField(primary_key=True)
    win=models.IntegerField()
    loss=models.IntegerField()
    kd=models.DecimalField(max_digits=5, decimal_places=2)
    debt=models.IntegerField()
    owed=models.IntegerField()

class UserGamingConfig(models.Model):

    user_gaming_config_id=models.AutoField(primary_key=True)
    dealer=models.CharField(max_length=30)
    table_color=models.CharField(max_length=30)
    charm=models.CharField(max_length=30)

class User(models.Model):

    MEMBERSHIP_CHOICES = [
        ('Br', 'Bronze'),
        ('Ag', 'Silver'),
        ('Au', 'Gold'),
        ('Di', 'Diamond')
    ]
    user_id=models.AutoField(primary_key=True)
    first_name=models.CharField(max_length=30)
    last_name=models.CharField(max_length=30)
    membership=models.CharField(max_length=30, choices=MEMBERSHIP_CHOICES)
    fk_gaming_data=models.ForeignKey(UserGamingData, on_delete=models.CASCADE)
    fk_gaming_config=models.ForeignKey(UserGamingConfig, on_delete=models.CASCADE)
    fk_resort_data=models.ForeignKey(UserResortData, on_delete=models.CASCADE)
    fk_resort_config=models.ForeignKey(UserResortConfig, on_delete=models.CASCADE)
    fk_account=models.ForeignKey(UserAccount, on_delete=models.CASCADE)
    fk_history=models.ForeignKey(UserHistory, on_delete=models.CASCADE)
    fk_auth=models.ForeignKey(UserAuth, on_delete=models.CASCADE)

I cannot seem to find anyone else online who has had the exact same error message if anyone could help i would greatly appreciate it

here is the entire output from the terminal

Operations to perform:
  Apply all migrations: admin, auth, contenttypes, gaming, resort, sessions, shared
Running migrations:
  Applying shared.0002_auto_20191213_0952...Traceback (most recent call last):
  File "/home/tabeals/.virtualenvs/resort_and_casino/local/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
psycopg2.errors.StringDataRightTruncation: value too long for type character varying(1)


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/tabeals/.virtualenvs/resort_and_casino/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
    utility.execute()
  File "/home/tabeals/.virtualenvs/resort_and_casino/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 375, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/tabeals/.virtualenvs/resort_and_casino/local/lib/python3.8/site-packages/django/core/management/base.py", line 323, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/tabeals/.virtualenvs/resort_and_casino/local/lib/python3.8/site-packages/django/core/management/base.py", line 364, in execute
    output = self.handle(*args, **options)
  File "/home/tabeals/.virtualenvs/resort_and_casino/local/lib/python3.8/site-packages/django/core/management/base.py", line 83, in wrapped
    res = handle_func(*args, **kwargs)
  File "/home/tabeals/.virtualenvs/resort_and_casino/local/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 232, in handle
    post_migrate_state = executor.migrate(
  File "/home/tabeals/.virtualenvs/resort_and_casino/local/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/tabeals/.virtualenvs/resort_and_casino/local/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/tabeals/.virtualenvs/resort_and_casino/local/lib/python3.8/site-packages/django/db/migrations/executor.py", line 245, in apply_migration
    state = migration.apply(state, schema_editor)
  File "/home/tabeals/.virtualenvs/resort_and_casino/local/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/tabeals/.virtualenvs/resort_and_casino/local/lib/python3.8/site-packages/django/db/migrations/operations/special.py", line 190, in database_forwards
    self.code(from_state.apps, schema_editor)
  File "/home/tabeals/code/resort_and_casino/shared/migrations/0002_auto_20191213_0952.py", line 16, in doit
    nice.save()
  File "/home/tabeals/.virtualenvs/resort_and_casino/local/lib/python3.8/site-packages/django/db/models/base.py", line 740, in save
    self.save_base(using=using, force_insert=force_insert,
  File "/home/tabeals/.virtualenvs/resort_and_casino/local/lib/python3.8/site-packages/django/db/models/base.py", line 777, in save_base
    updated = self._save_table(
  File "/home/tabeals/.virtualenvs/resort_and_casino/local/lib/python3.8/site-packages/django/db/models/base.py", line 850, in _save_table
    updated = self._do_update(base_qs, using, pk_val, values, update_fields,
  File "/home/tabeals/.virtualenvs/resort_and_casino/local/lib/python3.8/site-packages/django/db/models/base.py", line 900, in _do_update
    return filtered._update(values) > 0
  File "/home/tabeals/.virtualenvs/resort_and_casino/local/lib/python3.8/site-packages/django/db/models/query.py", line 760, in _update
    return query.get_compiler(self.db).execute_sql(CURSOR)
  File "/home/tabeals/.virtualenvs/resort_and_casino/local/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1429, in execute_sql
    cursor = super().execute_sql(result_type)
  File "/home/tabeals/.virtualenvs/resort_and_casino/local/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1100, in execute_sql
    cursor.execute(sql, params)
  File "/home/tabeals/.virtualenvs/resort_and_casino/local/lib/python3.8/site-packages/django/db/backends/utils.py", line 99, in execute
    return super().execute(sql, params)
  File "/home/tabeals/.virtualenvs/resort_and_casino/local/lib/python3.8/site-packages/django/db/backends/utils.py", line 67, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "/home/tabeals/.virtualenvs/resort_and_casino/local/lib/python3.8/site-packages/django/db/backends/utils.py", line 76, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "/home/tabeals/.virtualenvs/resort_and_casino/local/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "/home/tabeals/.virtualenvs/resort_and_casino/local/lib/python3.8/site-packages/django/db/utils.py", line 89, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/home/tabeals/.virtualenvs/resort_and_casino/local/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
django.db.utils.DataError: value too long for type character varying(1)

> this is my attempt to use the solution given by Alexandr Shurigin

from django.apps import apps
Tuser = apps.get_model('shared', 'User')
for field in Tuser._meta.get_fields():
     print([field.name, getattr(field, 'max_length', 'Not 
   Supported'), type(field)])

['user_id', None, <class 'django.db.models.fields.AutoField'>]
['first_name', 30, <class 'django.db.models.fields.CharField'>]
['last_name', 30, <class 'django.db.models.fields.CharField'>]
['membership', 30, <class 'django.db.models.fields.CharField'>]
['fk_gaming_data', None, <class 'django.db.models.fields.related.ForeignKey'>]
['fk_gaming_config', None, <class 'django.db.models.fields.related.ForeignKey'>]
['fk_resort_data', None, <class 'django.db.models.fields.related.ForeignKey'>]
['fk_resort_config', None, <class 'django.db.models.fields.related.ForeignKey'>]
['fk_account', None, <class 'django.db.models.fields.related.ForeignKey'>]
['fk_history', None, <class 'django.db.models.fields.related.ForeignKey'>]
['fk_auth', None, <class 'django.db.models.fields.related.ForeignKey'>]```

3
  • Can you post the entire output from your migrations. The error may be occuring during your migration, but User does not have a DateField Commented Dec 13, 2019 at 15:59
  • i added the entire output from the terminal at the bottom of my original post. thank you Commented Dec 13, 2019 at 16:14
  • Your foreign keys in the User model do not define its behavior for null. I typically add null=True to the definition so that it is not an error if i create and object without links to all of the related parts. Also temporally remove your migration and see if the database builds properly. The use the python manage.py shell to interact with your django installation and see if you can create a User object via the REPL environment first, before you create a migration to load data. Commented Dec 13, 2019 at 22:08

1 Answer 1

2

I believe that's because you are trying to pass user_id=True to the User model. Try to remove this kwarg completely from the statement since user_id is AutoField, Django manages auto-fields automatically

Second debug iteration :)

Ok, then I am sure that you are trying to run sql on not-migrated data, like "incorrect dependencies" are declared for the migration.

apps.get_model() returns not CURRENT MODEL STATE, it returns fake MODEL class for the "database models schema which is declared in dependencies".

Try to list your model fields and their lengths & etc using this code.

    for field in Tuser._meta.get_fields():
        print([field.name, getattr(field, 'max_length', 'Not Supported'), type(field)])

I think this way you will be able to find the wrong field passed :) Or even see what is the field name which causes the error.

Sign up to request clarification or add additional context in comments.

2 Comments

I tried that before and i get the same error. I jsut tried it again for good measure and i still get the same error. Everything else i read seems to reference the length of a character field but i cannot find anything that is set to 1. I was also thinking that it had to do with the choices field but when i removed that and ran it i go the same error.
thank you very much for your response but i am not sure what i am supposed to do with this print out. I added it to the post

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.