Opened 10 years ago

Closed 10 years ago

#8026 closed (invalid)

get_or_create fails on related queryset

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


The following will fail with a cryptic error message,

class Counter(models.Model):
  name = CharField(max_length = 255)

class Point(models.Model):
  counter = ForeignKey(Counter)

counter = Counter.objects.get(name = 'some name')
points  = counter.points.all()

For some reason, get_or_create ends up executing a SQL INSERT statement

  INSERT INTO 'point_table' ('counter_id') VALUES (None)

Well, that's not the exact output, which I unfortunately can't really copy and paste here, but the point is that get_or_create ends up inserting a Point with a None value for counter_id.

The quick fix right now is,

  counter = Counter.objects.get(name = 'some name')
  points  = counter.points.all()

  some_parameters.update({ 'defaults': { 'counter': counter } })

Change History (1)

comment:1 Changed 10 years ago by Michael Radziej

Component: Core frameworkDatabase wrapper
Resolution: invalid
Status: newclosed

Does it really insert None for counter_id (resulting in an SQL syntax error), or rather NULL (resulting still in an error due to the "not null" constraint)? If it's the first case, please reopen the ticket.

In the latter case, this is expected behaviour which is described in detail in the documentation about get_or_create. It does not make a sense to use a restricted query set like this.

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