Consider a simple model:
class Item(models.Model): name = models.CharField(...) unit_cost = models.DecimalField(...) unit_price = models.DecimalField(...)
It has the following admin class:
class ItemAdmin(admin.ModelAdmin): def queryset(self, request): qs = self.model._default_manager.get_query_set() qs2 = self.model._default_manager.raw(''' SELECT "stock_item"."id", "stock_item"."name", "stock_item"."unit_cost", "stock_item"."unit_price" FROM "stock_item" ''') qs3 = RawQuerySet(''' SELECT "stock_item"."id", "stock_item"."name", "stock_item"."unit_cost", "stock_item"."unit_price" FROM "stock_item" ''', self.model) return qs # WORKS return qs2 # DOESN'T WORK return qs3
I override the queryset () method to control the behavior of the admin list view. I want to execute a raw sql query in queryset (), map the results to the Item model before sending them to the list view. The problem is that returning qs2 or qs3 generates the following error in the template (without exception):
Database error Something wrong with your database installation. Make sure the appropriate database tables have been created, and make sure the database is readable by the appropriate user.
Keep in mind that a running raw request in a separate script works, for example:
items = Item._default_manager.raw(''' SELECT "stock_item"."id", "stock_item"."name", "stock_item"."unit_cost", "stock_item"."unit_price" FROM "stock_item" ''') for item in items: print item.name, item.unit_price # WORKS!
In fact, I have a big ambition to be able to create a kind of “virtual model” that does not have to have an appropriate database table whose purpose is to encapsulate sql projection queries in my admin class (so that the model can be displayed in it as list of administrators).
I tried a different approach, not using ItemAdmin, but instead using:
class ItemManager(models.Manager): def get_query_set(self): return Item._default_manager.raw(''' SELECT "stock_item"."id", "stock_item"."name", "stock_item"."unit_cost", "stock_item"."unit_price" FROM "stock_item" ''')
with:
class Item(models.Model): objects = ItemManager() etc...
But now I get a template exception in the admin list view:
"RawQuerySet" does not have the "complex_filter" attribute
What to do? Thanks...