I have created a new postgressql db in my django app within Heroku. Every time I run a migration, however, I get an error that I don't understand.
Error:
Applying argent.0043_auto_20170322_1629...Traceback (most recent call last):
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
psycopg2.ProgrammingError: cannot cast type date to integer
LINE 1: ...LTER COLUMN "date_id" TYPE integer USING "date_id"::integer,...
I have removed and added the only date field I have, to no avail. I still get the same error whether the date field in my models is there or not. Any insight would be much appreciated.
models.py
class Entry(models.Model):
date = models.DateField(blank=True, null=True,)
euros = models.CharField(max_length=500, blank=True, null=True)
comments = models.CharField(max_length=900, blank=True, null=True)
euros_sum = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True)
xrate = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True)
dollars_sum = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True)
daily_savings_dollars = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True)
daily_savings_display = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True)
def get_absolute_url(self):
return reverse('argent:detail', kwargs={'pk': self.pk})
def item_date(self):
row_title = self.date
return row_title
class Meta:
ordering = ['date']
traceback:
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line
utility.execute()
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 355, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv
self.execute(*args, **cmd_options)
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute
output = self.handle(*args, **options)
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 204, in handle
fake_initial=fake_initial,
File "/app/.heroku/python/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 "/app/.heroku/python/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 "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/executor.py", line 244, in apply_migration
state = migration.apply(state, schema_editor)
File "/app/.heroku/python/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 "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/operations/fields.py", line 215, in database_forwards
schema_editor.alter_field(from_model, from_field, to_field)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 513, in alter_field
old_db_params, new_db_params, strict)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/postgresql/schema.py", line 112, in _alter_field
new_db_params, strict,
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 674, in _alter_field
params,
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 119, in execute
cursor.execute(sql, params)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: cannot cast type date to integer
LINE 1: ...LTER COLUMN "date_id" TYPE integer USING "date_id"::integer,...
If want to migrate the date column from a integer type to to a datetime one, you need to handle any existing entries you have in the table before you can run the migration.
It's likely that you already have some integers in the date column when you try to change the column type, so the conversion fails as postgres doesn't know how to convert an integer to a datetime.
You can either delete all your entries if you don't care about them, or otherwise you need to break you migration into separate steps:
Create the new datetime column with a temporary name
Run a data migration to convert your integers into datetimes and populate the new column
Drop the old integer date column, rename the new one with the final name.
Related
So I have this app I wish to deploy to Heroku. I use django-heroku so it can run my postgres-sql stuff automatically.
I added release: python mannge.py migrate to my Procfile.
After the build, I get a deployment failed error, saying Release command failed. On opening the log, I have this error:
psycopg2.ProgrammingError: cannot cast type timestamp with time zone to integer
LINE 1: ...LUMN "established" TYPE integer USING "established"::integer
^
My model with the established field is like this:
from django.db import models
# Create your models here.
class FederalMinistry(models.Model):
full_name = models.CharField(max_length=400)
short_name = models.CharField(max_length=20)
description = models.TextField()
established = models.PositiveIntegerField()
# logo = models.ImageField(upload_to='fed_min_logos', blank=True, null=True, default='N/A')
current_minister = models.CharField(max_length=500)
permanent_secretary = models.CharField(max_length=500, default='N\A')
headquarters = models.CharField(max_length=100, default='Abuja')
twitter = models.URLField(blank=True, null=True, default='N/A')
website = models.URLField(blank=True, null=True, default='N/A')
class Meta:
verbose_name_plural = 'Federal Ministries'
def __str__(self):
return self.full_name
Please why am I getting the error and his to fix it. I have no knowledge of postgres.
Here is the full traceback as was requested:
/app/.heroku/python/lib/python3.6/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>.
""")
Operations to perform:
Apply all migrations: admin, airports, auth, contenttypes, federal_ministries, sessions, states, universities
Running migrations:
Applying federal_ministries.0002_auto_20190310_0129...Traceback (most recent call last):
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
psycopg2.ProgrammingError: cannot cast type timestamp with time zone to integer
LINE 1: ...LUMN "established" TYPE integer USING "established"::integer
^
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
utility.execute()
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 316, in run_from_argv
self.execute(*args, **cmd_options)
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 353, in execute
output = self.handle(*args, **options)
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped
res = handle_func(*args, **kwargs)
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 203, in handle
fake_initial=fake_initial,
File "/app/.heroku/python/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 "/app/.heroku/python/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 "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/executor.py", line 244, in apply_migration
state = migration.apply(state, schema_editor)
File "/app/.heroku/python/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 "/app/.heroku/python/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 "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 523, in alter_field
old_db_params, new_db_params, strict)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/postgresql/schema.py", line 122, in _alter_field
new_db_params, strict,
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 663, in _alter_field
params,
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 133, in execute
cursor.execute(sql, params)
File "/app/.heroku/python/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 "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/utils.py", line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
Q File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: cannot cast type timestamp with time zone to integer
LINE 1: ...LUMN "established" TYPE integer USING "established"::integer
And here is the federal_ministries.0002_auto_20190310_0129 migration file:
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('federal_ministries', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='federalministry',
options={'verbose_name_plural': 'Federal Ministries'},
),
migrations.AlterField(
model_name='federalministry',
name='established',
field=models.PositiveIntegerField(),
),
]
And the dependency 0001_initial file:
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='FederalMinistry',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('full_name', models.CharField(max_length=400)),
('short_name', models.CharField(max_length=20)),
('description', models.TextField()),
('established', models.DateTimeField()),
('current_minister', models.CharField(max_length=500)),
('permanent_secretary', models.CharField(default='N\\A', max_length=500)),
('headquarters', models.CharField(default='Abuja', max_length=100)),
('twitter', models.URLField(blank=True, default='N/A', null=True)),
('website', models.URLField(blank=True, default='N/A', null=True)),
],
),
]
I got it. I just needed to reset my migrations and delete the db.sqlite file, then ran migrations and migrate again. Fixed it!
If you are trying to cast a timestamp to PositiveIntegerField in PostgreSQL, you have to know that you can't.
Use a DateTimeField instead of a PositiveIntegerField for enstablished.
I think that this is related, take a look for further infos.
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 tried to insert a new field in my model and I got a DateTime Migration error, So I deleted those two fields and am trying to run "migrate" function which is not working , Make migration still work though.
D:\trydjango\src>python manage.py makemigrations
No changes detected
D:\trydjango\src>python manage.py migrate
Operations to perform:
Apply all migrations: contenttypes, auth, sessions, admin, posts
Running migrations:
Rendering model states... DONE
Applying posts.0009_auto_20170213_1754...Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "C:\python35\lib\site-packages\django\core\management\__init__.py", line
350, in execute_from_command_line
utility.execute()
File "C:\python35\lib\site-packages\django\core\management\__init__.py", line
342, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\python35\lib\site-packages\django\core\management\base.py", line 348,
in run_from_argv
self.execute(*args, **cmd_options)
File "C:\python35\lib\site-packages\django\core\management\base.py", line 399,
in execute
output = self.handle(*args, **options)
File "C:\python35\lib\site-packages\django\core\management\commands\migrate.py
", line 200, in handle
executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial)
File "C:\python35\lib\site-packages\django\db\migrations\executor.py", line 92
, in migrate
self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_ini
tial)
File "C:\python35\lib\site-packages\django\db\migrations\executor.py", line 12
1, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_
initial)
File "C:\python35\lib\site-packages\django\db\migrations\executor.py", line 19
8, in apply_migration
state = migration.apply(state, schema_editor)
File "C:\python35\lib\site-packages\django\db\migrations\migration.py", line 1
23, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, projec
t_state)
File "C:\python35\lib\site-packages\django\db\migrations\operations\fields.py"
, line 62, in database_forwards
field,
File "C:\python35\lib\site-packages\django\db\backends\sqlite3\schema.py", lin
e 221, in add_field
self._remake_table(model, create_fields=[field])
File "C:\python35\lib\site-packages\django\db\backends\sqlite3\schema.py", lin
e 103, in _remake_table
self.effective_default(field)
File "C:\python35\lib\site-packages\django\db\backends\base\schema.py", line 2
10, in effective_default
default = field.get_db_prep_save(default, self.connection)
File "C:\python35\lib\site-packages\django\db\models\fields\__init__.py", line
728, in get_db_prep_save
prepared=False)
File "C:\python35\lib\site-packages\django\db\models\fields\__init__.py", line
1461, in get_db_prep_value
value = self.get_prep_value(value)
File "C:\python35\lib\site-packages\django\db\models\fields\__init__.py", line
1440, in get_prep_value
value = super(DateTimeField, self).get_prep_value(value)
File "C:\python35\lib\site-packages\django\db\models\fields\__init__.py", line
1296, in get_prep_value
return self.to_python(value)
File "C:\python35\lib\site-packages\django\db\models\fields\__init__.py", line
1399, in to_python
parsed = parse_datetime(value)
File "C:\python35\lib\site-packages\django\utils\dateparse.py", line 93, in pa
rse_datetime
match = datetime_re.match(value)
TypeError: expected string or bytes-like object
D:\trydjango\src>
Below is my Models.py file.
from django.db import models
from django.core.urlresolvers import reverse
class Invoice(models.Model):
active = models.BooleanField()
bu_field = models.CharField(max_length=10)
invoice_name = models.CharField(max_length=500)
sow_name = models.CharField(max_length=500)
probability = models.IntegerField()
sow_type = models.CharField(max_length=50)
sow_start_date = models.DateField()
sow_end_date = models.DateField()
project_id = models.CharField(max_length=500)
project_manager = models.CharField(max_length=500, null=True)
po_number = models.IntegerField()
sow_value = models.DecimalField(max_digits=8, decimal_places=2)
current_month = models.CharField(max_length=20)
current_year = models.CharField(max_length=5)
month_value = models.DecimalField(max_digits=8, decimal_places=2)
q1_value = models.IntegerField()
q2_value = models.IntegerField()
q3_value = models.IntegerField()
q4_value = models.IntegerField()
total_value_ofyear = models.IntegerField()
probability_month_value = models.IntegerField()
def __str__(self):
return self.invoice_name
def get_absolute_url(self):
return reverse("invoice:detail", kwargs={"id": self.id})
There are no new fields , everything is back as it was but not i am getting this error.
I have a model:
class Season(models.Model):
""" Corresponds to your brochure publishing schedule, e.g. Fall/Winter 2012, Sprint 2014, etc. """
name = models.CharField(max_length=45, db_index=True, unique=True)
start_date = models.DateField(db_index=True, help_text="The date enrollment can begin this Season.")
<snip>
The model pre-dates migrations and I didn't use South.
The start_date field lived for many years with this definition
start_date = models.DateField(db_index=True, default=False,
help_text="The date of the first Session of this Season.")
I actually went in to edit the help text and noticed the default=False and thought, that doesnt make sense for a date field, it must have been a remnant from when I was dumb.
So I took that out.
Now my migration:
class Migration(migrations.Migration):
dependencies = [
('district', '0012_auto_20160622_1741'),
]
operations = [
migrations.AlterField(
model_name='season',
name='start_date',
field=models.DateField(help_text=b'The date enrollment can begin this Season.', db_index=True),
),
]
Fails with:
Applying district.0013_auto_20170204_1811...Traceback (most recent call last):
File "manage.py", line 9, in <module>
execute_from_command_line(sys.argv)
File "/verylongpathtovenv/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute_from_command_line
utility.execute()
File "/verylongpathtovenv/lib/python2.7/site-packages/django/core/management/__init__.py", line 346, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/verylongpathtovenv/lib/python2.7/site-packages/django/core/management/base.py", line 394, in run_from_argv
self.execute(*args, **cmd_options)
File "/verylongpathtovenv/lib/python2.7/site-packages/django/core/management/base.py", line 445, in execute
output = self.handle(*args, **options)
File "/verylongpathtovenv/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 222, in handle
executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial)
File "/verylongpathtovenv/lib/python2.7/site-packages/django/db/migrations/executor.py", line 110, in migrate
self.apply_migration(states[migration], migration, fake=fake, fake_initial=fake_initial)
File "/verylongpathtovenv/lib/python2.7/site-packages/django/db/migrations/executor.py", line 148, in apply_migration
state = migration.apply(state, schema_editor)
File "/verylongpathtovenv/lib/python2.7/site-packages/django/db/migrations/migration.py", line 115, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "/verylongpathtovenv/lib/python2.7/site-packages/django/db/migrations/operations/fields.py", line 201, in database_forwards
schema_editor.alter_field(from_model, from_field, to_field)
File "/verylongpathtovenv/lib/python2.7/site-packages/django/db/backends/base/schema.py", line 484, in alter_field
old_db_params, new_db_params, strict)
File "/verylongpathtovenv/lib/python2.7/site-packages/django/db/backends/base/schema.py", line 566, in _alter_field
old_default = self.effective_default(old_field)
File "/verylongpathtovenv/lib/python2.7/site-packages/django/db/backends/base/schema.py", line 211, in effective_default
default = field.get_db_prep_save(default, self.connection)
File "/verylongpathtovenv/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 710, in get_db_prep_save
prepared=False)
File "/verylongpathtovenv/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 1322, in get_db_prep_value
value = self.get_prep_value(value)
File "/verylongpathtovenv/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 1317, in get_prep_value
return self.to_python(value)
File "/verylongpathtovenv/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 1274, in to_python
parsed = parse_date(value)
File "/verylongpathtovenv/lib/python2.7/site-packages/django/utils/dateparse.py", line 60, in parse_date
match = date_re.match(value)
TypeError: expected string or buffer
Researching TypeError: expected string or buffer comes up with a discussion about not doing what I'm trying to undo, i.e, don't set the default for a date field to something not date-like.
Not clear how to proceed with this. Any tips would be appreciated.
Determine what the default is in the database
cd /path/to/project
python manage.py dbshell
mysql> show create table district_season\G
# or for postgres
# pg_dump -t 'schema.district_season' --schema-only database-name
If there is no problem with the type, run the migration with --fake
./manage.py migrate district --fake
which will mark the migration as having been run without doing anything to the database.
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