Opened 3 years ago

Closed 3 years ago

Last modified 3 years ago

#18778 closed Bug (invalid)

ForeignKey to a model with a CharField primary key produces unexpected results for an empty-string PK value

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


class ModelA(models.Model):
    code = models.CharField(max_length=50, primary_key=True)

class ModelB(models.Model):
    model_a = models.ForeignKey(ModelA, blank=True, null=True, max_length=50)

In this case, if there's an instance of ModelA such that instance_a.code == '', ModelB will not be able to reference it properly. Upon save, db.models.fields.related.ForeignKey will change model_a_id from '' to NULL. While this is an odd case, and I don't particularly like the situation of having an empty string as a primary key, I think Django should at least be able to handle it. The offending code is at

Change History (3)

comment:1 Changed 3 years ago by Ubercore

  • Cc Ubercore added
  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset

comment:2 Changed 3 years ago by anonymous

  • Resolution set to invalid
  • Status changed from new to closed

You cannot have a empty primary_key.
Can you provide a failing test for this ?

comment:3 Changed 3 years ago by Ubercore

Interesting. This project must have gotten into an odd state with migrations. I'll investigate a bit more, but it does look like an invalid ticket. Thanks.

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