Can't create a record with a Foreign Key: IntegrityError: (1048, "Column 'user_id' cannot be null")

2,631 views
Skip to first unread message

Theme Park Photo, LLC

unread,
Feb 3, 2009, 1:22:34 AM2/3/09
to Django users
I can't get anything with Foreign keys to work. I trimmed everything
down to the simplest example:

from django.db import models
from django.contrib.auth.models import User

class Ranking(models.Model):
user = models.ForeignKey(User)
score = models.IntegerField()
def __unicode__(self):
return u'%s %d' % (self.user, self.score)

I can't add any "Ranking" records. I try like this (from the django
shell) and always get an error like this:
IntegrityError: (1048, "Column 'user_id' cannot be null")

Can someone give me a hint as to the right way to do this?

(Django shell session below)

>>> from django.db import models
>>> from django.contrib.auth.models import User
>>> from djbaytzim.bayscore.models import Ranking
>>> u = User (username="swirsky")
>>> print type(u)
<class 'django.contrib.auth.models.User'>
>>> r = Ranking(user=u, score=10)
>>> r.save()
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Library/Python/2.5/site-packages/django/db/models/base.py",
line 311, in save
self.save_base(force_insert=force_insert,
force_update=force_update)
File "/Library/Python/2.5/site-packages/django/db/models/base.py",
line 383, in save_base
result = manager._insert(values, return_id=update_pk)
File "/Library/Python/2.5/site-packages/django/db/models/
manager.py", line 138, in _insert
return insert_query(self.model, values, **kwargs)
File "/Library/Python/2.5/site-packages/django/db/models/query.py",
line 894, in insert_query
return query.execute_sql(return_id)
File "/Library/Python/2.5/site-packages/django/db/models/sql/
subqueries.py", line 309, in execute_sql
cursor = super(InsertQuery, self).execute_sql(None)
File "/Library/Python/2.5/site-packages/django/db/models/sql/
query.py", line 1734, in execute_sql
cursor.execute(sql, params)
File "/Library/Python/2.5/site-packages/django/db/backends/util.py",
line 19, in execute
return self.cursor.execute(sql, params)
File "/Library/Python/2.5/site-packages/django/db/backends/mysql/
base.py", line 88, in execute
raise Database.IntegrityError(tuple(e))
IntegrityError: (1048, "Column 'user_id' cannot be null")


Malcolm Tredinnick

unread,
Feb 3, 2009, 1:39:29 AM2/3/09
to django...@googlegroups.com
On Mon, 2009-02-02 at 22:22 -0800, Theme Park Photo, LLC wrote:
> I can't get anything with Foreign keys to work. I trimmed everything
> down to the simplest example:
>
> from django.db import models
> from django.contrib.auth.models import User
>
> class Ranking(models.Model):
> user = models.ForeignKey(User)
> score = models.IntegerField()
> def __unicode__(self):
> return u'%s %d' % (self.user, self.score)
>
> I can't add any "Ranking" records. I try like this (from the django
> shell) and always get an error like this:
> IntegrityError: (1048, "Column 'user_id' cannot be null")
>
> Can someone give me a hint as to the right way to do this?
>
> (Django shell session below)
>
> >>> from django.db import models
> >>> from django.contrib.auth.models import User
> >>> from djbaytzim.bayscore.models import Ranking
> >>> u = User (username="swirsky")
> >>> print type(u)
> <class 'django.contrib.auth.models.User'>

You have to save the User object before you can use it anywhere. At this
point in time, it doesn't have a primary key value, which is what the
Ranking object needs to refer to it. Actually, the pk value is None,
which 'r' then uses, which causes problems later.

Another way of thinking of this: right now, 'u' does not exist in the
database. So you cannot save 'r' to the database, since it needs to
refer to another row in the database (the one for 'u', which doesn't
exist) for the User object.

Call u.save() here (or use User.objects.create(username="swirsky")) and
everything will work.

Regards,
Malcolm


Theme Park Photo, LLC

unread,
Feb 3, 2009, 10:59:37 AM2/3/09
to Django users
Thanks! That was a little unintuitive because, of course, I was only
trying to do a "SELECT" on u and an INSERT on R. Save seems like it
would do something to u



On Feb 2, 10:39 pm, Malcolm Tredinnick <malc...@pointy-stick.com>
wrote:

Theme Park Photo, LLC

unread,
Feb 3, 2009, 11:02:06 AM2/3/09
to Django users

In fact, not only is it unintuitive...it doesn't work! If I try to do
a u.save() first, or a User.objects.create(username="swirsky") I get a
IntegrityError: (1062, "Duplicate entry 'swirsky' for key 2")

So there's something else wrong!

Theme Park Photo, LLC

unread,
Feb 3, 2009, 11:08:07 AM2/3/09
to Django users

Ok! NOW I get it! You need to do a get to do a select by primary key


u=User.objects.get(username="swirsky")


For some reason I thought that you could get by primary key by just
creating the object with the key specified...

Malcolm Tredinnick

unread,
Feb 3, 2009, 8:41:17 PM2/3/09
to django...@googlegroups.com

Your first version of the code was creating a Python instance. No
interaction with the database. Your new version specifically asks the
database for information.

Malcolm


Reply all
Reply to author
Forward
0 new messages