﻿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
13212	get_or_create() does not respect to_field setting	cheerios	nobody	"A model with a ForeignKey defining a to_field always results in a new record creation with get_or_create(), as the to_field -setting for is ignored and the initial SELECT uses ForeignKey's primary_key. The Field defined with to_field does not even have the same Field -type (IntegerField looked up against CharField).

{{{
from django.db import models
import uuid
class UniqueField(models.CharField):
    def pre_save(self, model_instance, add):
        value = getattr(model_instance, self.attname, None)
        if not value:
            value = unicode(uuid.uuid1())
            setattr(model_instance, self.attname, value)
        return value

class Base(models.Model):
    pub_date = models.DateTimeField(auto_now_add=True)
    class Meta:
        abstract = True

class Sun(Base):
    unique = UniqueField(max_length=36, editable=False, null=False, blank=False, unique=True)

class Dae(models.Model):
    pub_date = models.DateTimeField(auto_now_add=True)
    sun = models.ForeignKey(Sun, blank=True, null=True, to_field='unique')

}}}

{{{
sun = Sun()
sun.save()
dae = Dae.objects.get_or_create(sun=sun)
 SELECT `main_dae`.`id`, `main_dae`.`pub_date`, `main_dae`.`sun_id` FROM `main_dae` WHERE `main_dae`.`sun_id` = 1     # (!) using primary_key value, should be using to_field='unique'!
 INSERT INTO `main_dae` (`pub_date`, `sun_id`) VALUES ('2010-03-25 20:55:36', 'b655a54e-3850-11df-b6cc-001b11b72424')
dae = Dae.objects.get_or_create(sun=sun)
 SELECT `main_dae`.`id`, `main_dae`.`pub_date`, `main_dae`.`sun_id` FROM `main_dae` WHERE `main_dae`.`sun_id` = 1     # (!) using primary_key value, should be using to_field='unique'!
 INSERT INTO `main_dae` (`pub_date`, `sun_id`) VALUES ('2010-03-25 20:55:36', 'b655a54e-3850-11df-b6cc-001b11b72424') # (!) this record should never get created with correct selects
}}}

"		closed	Database layer (models, ORM)	1.1		duplicate	to_field, get_or_create, relation		Unreviewed	0	0	0	0	0	0
