Code

Opened 6 years ago

Closed 6 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:

Description

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()
points.get_or_create(**some_parameters)

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 } })
  points.get_or_create(**some_parameters)

Attachments (0)

Change History (1)

comment:1 Changed 6 years ago by mir

  • Component changed from Core framework to Database wrapper
  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset
  • Resolution set to invalid
  • Status changed from new to closed

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.

Add Comment

Modify Ticket

Change Properties
<Author field>
Action
as closed
as The resolution will be set. Next status will be 'closed'
The resolution will be deleted. Next status will be 'new'
Author


E-mail address and user name can be saved in the Preferences.

 
Note: See TracTickets for help on using tickets.