[Django]-Django: how to map the results of a raw sql query to model instances in admin list view?

1👍

Solved.

The simplest approach was to create a database view in sqlite3 (the db backend I’m using) and then add a normal model with a name compatible with the view. The model must have a set of fields with similar names to those of fields returned by the view. No admins or managers are necessary for my purposes.

View creation db script:

CREATE VIEW <view_name> AS SELECT etc...

View dropping db script (run as a preliminary step in case you need to re-create the view):

DROP VIEW <view_name>

The only thing you gotta be careful about when creating the view is to make sure you set:

class Meta:
    managed = False
    #ordering = ( '-date', )

so as not to create the table when syncdb is run.

One more thing, you need to pick a unique field in your view as a primary key (and reflect that in the model) otherwise django will complain with something like:

no such column: stock_itemdbview.id

Cheers!

0👍

Well looking at the src, QuerySet and RawQuerySet are similar but very different classes where a QuerySet trumps a RawQuerySet in terms of provided functionality.

If I understand this correctly the last error you mention is understandable as a RawQuerySet does not have the complex_filter method and I presume you are at somepoint calling model.objects.filter which I believe invokes the aforementioned.

It is also understandable how you can iterate over a RawQuerySet, because, for want of a better term, the ‘core model’ is still represented in a RawQuerySet as it would be in a QuerySet.

Would using extra() not suffice?

I’m still pondering over the first issue will come back if/when I find one.

👤T I

Leave a comment