Opened 16 years ago
Closed 16 years ago
#8026 closed (invalid)
get_or_create fails on related queryset
Reported by: | Owned by: | nobody | |
---|---|---|---|
Component: | Database layer (models, ORM) | Version: | dev |
Severity: | Keywords: | ||
Cc: | Triage Stage: | Unreviewed | |
Has patch: | no | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | no | UI/UX: | no |
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)
Change History (1)
comment:1 by , 16 years ago
Component: | Core framework → Database wrapper |
---|---|
Resolution: | → invalid |
Status: | new → closed |
Note:
See TracTickets
for help on using tickets.
Does it really insert
None
forcounter_id
(resulting in an SQL syntax error), or ratherNULL
(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.