to_field can not use primary key of related object.

12 views
Skip to first unread message

yillkid

unread,
Aug 23, 2012, 2:30:54 AM8/23/12
to django...@googlegroups.com


HI all.
I write a model:
class UserGroup(models.Model):
        groups = models.ForeignKey(Group, to_field='id')

and when I into admin backend:












According to the Django  document the combobox item should be a "id" field in Group model,
but it is not, why ?

Jani Tiainen

unread,
Aug 23, 2012, 3:09:26 AM8/23/12
to django...@googlegroups.com
23.8.2012 9:30, yillkid kirjoitti:
>
> HI all.
> I write a model:
> class UserGroup(models.Model):
> groups = models.ForeignKey(Group, to_field='id')
>
> and when I into admin backend:
>
> <https://lh4.googleusercontent.com/-dxgts8I14Sw/UDXNrsM0CZI/AAAAAAAAAoA/6DQxSeD2mOw/s1600/123.jpeg>
>
>
>
>
>
>
>
>
>
>
>
>
> According to the Django document the combobox item should be a "id"
> field in Group model,
> but it is not, why ?

Where from the documenttion you got impression of that? As documentation
states:

"Foreginkey.to_field
The field on the related object that the relation is to. By default,
Django uses the primary key of the related object"

There is nothing about representation in a select field on a form. It
still uses ID as a value to post. But what you see is just a
representation of the __unicode__ method. There is way to change that
behaviour for a particular form field if needed.

--
Jani Tiainen

- Well planned is half done and a half done has been sufficient before...
Reply all
Reply to author
Forward
0 new messages