Optional foreign key with django?

2,817 views
Skip to first unread message

maroxe

unread,
Sep 8, 2010, 4:14:49 PM9/8/10
to Django users
Hi, In my models I want to have an optional field to a foreign key. I
tried this:

field = models.ForeignKey(MyModel, null=True, blank=True,
default=None)

But i am getting this error:

model.mymodel_id may not be NULL

i am using sqlite edit: if it can help, here is the exception
location:

/usr/lib/python2.6/site-packages/django/db/backends/sqlite3/base.py
in execute, line 200

so it's sqlite specific problem, i think.

PS: i droped the whole table and synced before getting this error.

akaariai

unread,
Sep 9, 2010, 5:00:29 AM9/9/10
to Django users
This should just work (TM). Are you sure the table is dropped and
recreated correctly? The error is from the database (not from Django
code), and the reason is a not null constraint on models.mymodel_id
which should not exist. Maybe you could try this in completely clean
database?

- Anssi

bagheera

unread,
Sep 9, 2010, 7:04:35 AM9/9/10
to django...@googlegroups.com

I have same problem with sqlite. Try another database. Django devs suggest
postgres.
--
Linux user

Carlton Gibson

unread,
Sep 9, 2010, 8:18:48 AM9/9/10
to django...@googlegroups.com

On 9 Sep 2010, at 12:04, bagheera wrote:

>> On Sep 8, 11:14 pm, maroxe <bachir...@gmail.com> wrote:
>>> Hi, In my models I want to have an optional field to a foreign key. I
>>> tried this:
>>>
>>> field = models.ForeignKey(MyModel, null=True, blank=True,
>>> default=None)
>>>
>>> But i am getting this error:
>>>
>>> model.mymodel_id may not be NULL


I think the error is that SQLite treats columns with defaults as NOT NULL.

As far as I can see, you don't need the `default=None` in your model declaration. Change it to:

field = models.ForeignKey(MyModel, null=True, blank=True)

-- I have multiple apps using SQLite that do exactly this, so to quote an earlier post, "this should just work (TM)"

HTH

Regards,
Carlton

maroxe

unread,
Sep 9, 2010, 7:16:04 PM9/9/10
to Django users
This solved my problem
Reply all
Reply to author
Forward
0 new messages