Opened 8 years ago

Closed 8 years ago

#13083 closed (duplicate)

Add foreignkey_id field resolving to queryset filter function

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



When selecting a model instance using a field that is a foreign key to a model, I expected this to work:

>>> AModel.objects.get(somemodel_id=4)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "d:\code\env\src\django\django\db\models\", line 132, in get
    return self.get_query_set().get(*args, **kwargs)
  File "d:\code\env\src\django\django\db\models\", line 331, in get
    clone = self.filter(*args, **kwargs)
  File "d:\code\env\src\django\django\db\models\", line 545, in filter
    return self._filter_or_exclude(False, *args, **kwargs)
  File "d:\code\env\src\django\django\db\models\", line 563, in _filter_or_exclude
    clone.query.add_q(Q(*args, **kwargs))
  File "d:\code\env\src\django\django\db\models\sql\", line 1109, in add_q
  File "d:\code\env\src\django\django\db\models\sql\", line 1003, in add_filter
    negate=negate, process_extras=process_extras)
  File "d:\code\env\src\django\django\db\models\sql\", line 1171, in setup_joins
    "Choices are: %s" % (name, ", ".join(names)))
FieldError: Cannot resolve keyword 'somemodel_id' into field. Choices are: a, b, c, id, somemodel

I understand why it doesn't - you need two underscores to follow references:

>>> AModel.objects.get(somemodel__id=4)
<AModel: TheModelIWanted>

But this feels like an asymmetry, since after you get the model, you can read / assign to the foreignkey's id:

>>> obj = AModel.objects.get(somemodel__id=4)
>>> obj.somemodel
<SomeModel: OtherModel>
>>> obj.somemodel_id #Specifically this - why does this work, but I can't query for it without the JOIN to the related table?

This asymmetry also /not/ around for the creation of a new instance:

>>> AModel(somemodel_id=4)
<AModel: UnsetPlaceholder>

Is this a design decision? Implementation detail?

Change History (2)

comment:1 Changed 8 years ago by anonymous

Also, in my case, the search fields are coming from a dict, so i'm querying as

obj = self.get(**searchdict)

which fails.

searchdict is also used during creation if a result isn't found, like this:

obj = self.model(**searchdict)

which works.

comment:2 Changed 8 years ago by Karen Tracey

Resolution: duplicate
Status: newclosed

This is #5535, I believe.

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