foreign keys - Django ForeignKey null=True fails to drop not null from column -
the problem:
here's class 2 foreignkey
s (dept
, salary_range
). note null=true
:
class userprofile(models.model): user = models.onetoonefield(user, related_name='user_profile') avatar = models.charfield(max_length=300, default='/static/default.png') dept = models.foreignkey(department, null=true) salary_range = models.foreignkey(salaryrange, null=true)
running python manage.py sqlall main
seems show correct sql (no not null
on dept_id
, salary_range_id
:
create table "main_userprofile" ( "id" integer not null primary key, "user_id" integer not null unique references "auth_user" ("id"), "avatar" varchar(300) not null, "dept_id" integer references "main_department" ("id"), "salary_range_id" integer references "main_salaryrange" ("id"),
but integrityerror
occurs when creating userprofile
:
main_userprofile.dept_id may not null
and upon inspection of database, both columns set not null
. how? why?
the hack:
all have been able come alter table after syncdb
:
alter table main_userprofile alter column dept_id drop not null; alter table main_userprofile alter column salary_range_id drop not null;
this works postgres, sqlite not have alter column
option..
the solution ??
everything seems fine. suggested in comment, when ran syncdb
first time, @ time did not had options null=true
dept
, salary_range
. changed code did not modify table definition. solve that, can either manually fix issue dropping not null
part or can use database migrations apps. popular 1 far south. south can detect changes in model definitions , apply appropriate changes database (called database migrations) without loosing data. south docs pretty should able start using in no time.
ps - in future versions of django (most django 1.7), migrations capability integrated directly django core until then, south have do.
Comments
Post a Comment