How to create a QuerySet from raw SQL query?

3,145 views
Skip to first unread message

wierob83

unread,
May 23, 2009, 4:35:12 AM5/23/09
to Django users
Hi,

how can I obtain a QuerySet from a raw SQL query?

I want to use some generic views (objects list, object detail).
Unfortunately, all examples I've seen require a QuerySet (e.g.
MyModel.objects.all()). I'm using an existing database and already
have SQL queries that I want to use. So how can I get a QuerySet from
the SQL query?

Thanks in advance.

kind regards
robert

Daniel Roseman

unread,
May 23, 2009, 8:23:29 AM5/23/09
to Django users
That depends on what your SQL query is returning. If it's a list of
IDs, you can make another query via the ORM to get the objects you
need:
queryset = MyModel.objects.filter(id__in=[list_of_ids])

If it's returning all the columns in the model, you can simply
instantiate the objects using that data:
queryset = [MyModel(*row) for row in results]
Here, *row passes the list of columns in the 'row' variable to the
constructor for MyModel. This is basically what the Django internals
do anyway. To make this work, the columns have to be in the same order
as in the model definition.

--
DR.
Reply all
Reply to author
Forward
0 new messages