in my Database (psql) I’ve got a table named offers_offer
and inside that there is an column named offer_name
, which is wrong, because it should actually be just name
. I don’t know why it has this name, but due to this I can’t load any fixtures or create a new object, because I always receive the error that name
wasn’t found (obviously).
Now my model looks like this:
class Offer(models.Model):
name = models.CharField(default="", verbose_name='Offer Name', blank=False, max_length=255)
(some other fields )
and my ONLY initial migration looks like this:
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
('crm', '0007_make_gender_mandatory'),
]
operations = [
migrations.CreateModel(
name='Offer',
fields=[
('name', models.CharField(default='', max_length=255, verbose_name='Offer Name')),
(every other field )
],
options={
(some options )
},
),
]
So I don’t really know why it’s named offer_name
in my db, while this was created to have name
as field name.
Anyway I tried to fix that by making a new migration like:
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('offers', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='offer',
name='offer_name',
field=models.CharField(default='', db_column=b'offer_name', max_length=255, verbose_name='Offer Name'),
),
migrations.RenameField(
model_name='offer',
old_name='offer_name',
new_name='name',
),
]
But if I do that, I just get a FieldDoesNotExist Error which states me that django.core.exceptions.FieldDoesNotExist: Offer has no field named 'offer_name'
So does someone know a good way to fix that?
Advertisement
Answer
You could change the model to accomodate for your custom column with the db_column
argument like so:
name = models.CharField(default="", verbose_name='Offer Name', blank=False, max_length=255, db_column="offer_name")
To elaborate a little bit more: The db_colum
parameter can be used with every default django field. When it is used django disregards it`s default naming scheme and just looks up whatever name you passed.