﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
10243	to_field option problems in admin site	tsawyer	Malcolm Tredinnick	"The inline admin code seems to have a problem when using a to_field in the model definition.  Given the following model:
{{{
class Users(models.Model):
    use_serial = models.DecimalField(decimal_places=0, max_digits=10, db_column='USE_SERIAL', primary_key=True)
    use_oracle_user = models.CharField(max_length=12, db_column='USE_ORACLE_USER', unique=True)
    
    def __unicode__(self):
        return self.use_oracle_user
              
class UserAtSites(models.Model):
    uas_serial = models.DecimalField(decimal_places=0, max_digits=10, db_column='UAS_SERIAL', primary_key=True)
    uas_sit_serial = models.IntegerField(db_column='UAS_SIT_SERIAL')
    uas_use_oracle_user = models.ForeignKey(Users, to_field='use_oracle_user', db_column='UAS_USE_ORACLE_USER')

    def __unicode__(self):
        return '%s, %s' %(self.uas_sit_serial, self.uas_use_oracle_user)
}}}
and the following admin settings:
{{{
class UserAtSitesInline(admin.StackedInline):
  model = UserAtSites

class UsersAdmin(admin.ModelAdmin):
  inlines = [UserAtSitesInline]

class UserAtSiteAdmin(admin.ModelAdmin):
  pass

admin.site.register(Users, UsersAdmin)
admin.site.register(UserAtSites, UserAtSiteAdmin)
}}}
The inline admin is not finding the related objects by the foreign key uas_use_oracle_user.  This appears to be because the query is selecting by the primary key (use_serial) rather than the declared to_field (use_oracle_user).  The raw sql is logged as uas_use_oracle_user = 1 where we expect uas_use_oracle_user = 'tjs'.

I suspect that this is an inline admin problem, as doing the same sort of thing manually appears to work:
{{{
  lNewUser = Users()
  lNewUser.use_serial = 1
  lNewUser.use_oracle_user = 'tjs'
  lNewUser.save()

  lNewUserAtSites = UserAtSites()
  lNewUserAtSites.uas_serial = 10
  lNewUserAtSites.uas_sit_serial = 123
  lNewUserAtSites.uas_use_oracle_user = lNewUser
  lNewUserAtSites.save()

  lSelectedUser = UserAtSites.objects.all()[0]
  print lNewUserAtSites.uas_use_oracle_user_id  # correctly prints tjs
  print lSelectedUser.uas_use_oracle_user.use_serial  # correctly prints 1
}}}

We're also getting three fields in the inline admin section, one labelled uas serial, the next uas_sit_serial and the final one doesn't have a label.

Tested with svn revision 9826"		closed	Database layer (models, ORM)	dev		fixed	to_field	Florian Apolloner	Accepted	0	0	0	0	0	0
