Opened 15 years ago

Closed 15 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: dev
Severity: Keywords: foreignkey, filter
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Hi,

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\manager.py", line 132, in get
    return self.get_query_set().get(*args, **kwargs)
  File "d:\code\env\src\django\django\db\models\query.py", line 331, in get
    clone = self.filter(*args, **kwargs)
  File "d:\code\env\src\django\django\db\models\query.py", line 545, in filter
    return self._filter_or_exclude(False, *args, **kwargs)
  File "d:\code\env\src\django\django\db\models\query.py", line 563, in _filter_or_exclude
    clone.query.add_q(Q(*args, **kwargs))
  File "d:\code\env\src\django\django\db\models\sql\query.py", line 1109, in add_q
    can_reuse=used_aliases)
  File "d:\code\env\src\django\django\db\models\sql\query.py", line 1003, in add_filter
    negate=negate, process_extras=process_extras)
  File "d:\code\env\src\django\django\db\models\sql\query.py", 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?
4L
>>> obj.somemodel.id
4L

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 by anonymous, 15 years ago

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 by Karen Tracey, 15 years ago

Resolution: duplicate
Status: newclosed

This is #5535, I believe.

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