Django ForeignKey to_field vs. db_column

5,019 views
Skip to first unread message

Artur Ergashev

unread,
Sep 14, 2009, 2:19:43 PM9/14/09
to Django users
I'm working on some models for a legacy database structure, and am
having a road_block with Foreign Keys and non-conventional names.

As I understand it, if in my model I have something like:

something = ForeignKey(something)

then django will look for the something_id field in my table when
looking for the relationship. However, if my table has
anotherthing_id, I would have to explicitly define that name. The
documentation has me believe that I would do:

something = ForeignKey(something, to_field='anotherthing_id')

however it doesn't seem to work this well, Django (particularly the
admin) appears to want to find something_id. Here's the concrete case
in my code:

# site table
# site_id (PK)
# ...

# core.Site
class Site(models.Model):
id = models.IntegerField(primary_key=True, db_column='site_id')

# member.User
class User(models.Model):
#I already have a attribute in this model called site, so I can't
just do site = ... as it wouldn't be descriptive enough even if I
wouldn't have a conflict
last_login_site_id = models.ForeignKey('core.Site',
to_field='site_id', related_name='site_last_login_users')

The error I get:

Caught an exception while rendering: (1054, "Unknown column
'user.last_login_site_id_id' in 'field list'")

However when I change the User model to:

class User(models.Model):
#I already have a attribute in this model called site, so I can't
just do site = ... and it isn't descriptive anyway...
last_login_site_id = models.ForeignKey('core.Site',
db_column='site_id', related_name='site_last_login_users')

everything seems to work fine. This is confusing to me since I thought
to_field was the attribute I needed, and db_column isn't documented as
a keyword argument for ForeignKey (I assume it's inherited somehow or
undocumented).

Am I doing something horribly wrong? Or did I just misunderstand the
model docs?

Thanks!

Daniel Roseman

unread,
Sep 14, 2009, 2:56:35 PM9/14/09
to Django users
Yes, you've misunderstood. to_field is the column in the related table
which your foreignkey is pointing to. So, for example, if your Site
table had a column site_name, and you wanted the value of your FK to
be taken from that field rather than the primary key for some reason,
you would set to_field to 'site_name'. It doesn't change the name of
the underlying field in the current model.

db_column is documented under the list of attributes which are common
to all fields, here:
http://docs.djangoproject.com/en/dev/ref/models/fields/#common-model-field-options
--
DR.
Reply all
Reply to author
Forward
0 new messages