l0b0
l0b0

Reputation: 58778

Wrapping a Django query set in a raw query or vice versa?

I'm thinking of using a raw query to quickly get around limitations with either my brain or the Django ORM, but I don't want to redevelop the infrastructure required to support the existing ORM code such as filters. Right now I'm stuck with two dead ends:

  1. Writing an inner raw query and reusing that like any other query set. Even though my raw query selects the correct columns, I can't filter on it:

    AttributeError: 'RawQuerySet' object has no attribute 'filter'

    This is corroborated by another answer, but I'm still hoping that that information is out of date.

  2. Getting the SQL and parameters from the query set and wrapping that in a raw query. It seems the raw SQL should be retrievable using queryset.query.get_compiler(DEFAULT_DB_ALIAS).as_sql() - how would I get the parameters as well (obviously without actually running the query)?

Upvotes: 1

Views: 762

Answers (1)

Matthew Schinckel
Matthew Schinckel

Reputation: 35609

One option for dealing with complex queries is to write a VIEW that encapsulates the query, and then stick a model in front of that. You will still be able to filter (and depending upon your view, you may even get push-down of parameters to improve query performance).

All you need to do to get a model that is backed by a view is have it as "unmanaged", and then have the view created by a migration operation.

It's better to try to write a QuerySet if you can, but at times it is not possible (because you are using something that cannot be expressed using the ORM, for instance, or you need to to something like a LATERAL JOIN).

Upvotes: 1

Related Questions