Opened 5 years ago

Closed 5 years ago

Last modified 3 years ago

#13363 closed (wontfix)

extra fields of Model.objects.extra() can't be filtered

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


sepp = SomeModel.objects.extra(select={'hiho': """(6371 * acos(cos( radians(%f) ) 
* cos( radians( geo_lat ) ) * cos( radians( geo_long ) - radians(%f) ) 
+ sin( radians(%f) ) * sin( radians( geo_lat ) ) ))""" % (latitude, longitude, latitude)})

throws an exception:

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/django/db/models/", line 550, in filter
    return self._filter_or_exclude(False, *args, **kwargs)
  File "/django/db/models/", line 568, in _filter_or_exclude
    clone.query.add_q(Q(*args, **kwargs))
  File "/django/db/models/sql/", line 1131, in add_q
  File "/django/db/models/sql/", line 1026, in add_filter
    negate=negate, process_extras=process_extras)
  File "/django/db/models/sql/", line 1194, in setup_joins
    "Choices are: %s" % (name, ", ".join(names)))
FieldError: Cannot resolve keyword 'hiho' into field. Choices are: ...all the fields of the model

Change History (4)

comment:1 Changed 5 years ago by Alex

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset
  • Resolution set to wontfix
  • Status changed from new to closed

This is intentional, you need to use the where option of extra() to filter by extra select items.

comment:2 Changed 5 years ago by ris

  • Resolution wontfix deleted
  • Status changed from closed to reopened

Sorry I know it's impolite to reopen tickets like this.

I too would find this a very useful feature.

I realize _similar_ functionality is possible using the where= clause, but allowing the selected parameter to be filtered against would mean you could re-use the same calculated parameter (multiple times) from within complex Q() statements.

e.g. - currently in my app I am dynamically building a really very complex query using Q statements. Having to fall back to the QuerySet to perform the extra() from within this code would be quite painful and screw up my encapsulation.

comment:3 Changed 5 years ago by russellm

  • Resolution set to wontfix
  • Status changed from reopened to closed

As Alex notes, this behavior is intentional. extra() is designed for inserting specific SQL into a query, not as a generic extension mechanism for the ORM.

It sounds like what you actually want is the ability to include model annotations that aren't aggregates.

comment:4 Changed 3 years ago by akaariai

  • Component changed from ORM aggregation to Database layer (models, ORM)
Note: See TracTickets for help on using tickets.
Back to Top