Opened 15 years ago

Closed 15 years ago

Last modified 13 years ago

#13212 closed (duplicate)

get_or_create() does not respect to_field setting

Reported by: cheerios Owned by: nobody
Component: Database layer (models, ORM) Version: 1.1
Severity: Keywords: to_field, get_or_create, relation
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

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

Change History (2)

comment:1 by Karen Tracey, 15 years ago

Resolution: duplicate
Status: newclosed

I believe the root problem here is #11319.

comment:2 by Jacob, 13 years ago

milestone: 1.3

Milestone 1.3 deleted

Note: See TracTickets for help on using tickets.
Back to Top