Django QuerySet从sql表函数中选择的方法
大家。
我使用 Django 1.3 和 Postgres 9.0。我有非常复杂的 sql 查询,它使用一些额外的字段扩展了简单的模型表查找。由于它是参数化的,因此它包装在表函数中。
一个月前,我设法在原始查询的帮助下使其工作,但 RawQuerySet 缺乏许多我真正需要的功能(过滤器、count() 和clone() 方法、可链接性)。
这个想法看起来很简单。 QuerySet 允许我执行此查询:
SELECT "table"."field1", ... ,"table"."fieldN" FROM "table"
而我需要执行此操作:
SELECT "table"."field1", ... ,"table"."fieldN" FROM proxy(param1, param2)
所以问题是: 我该如何执行此操作?我已经开始创建自定义管理器,但无法用自定义字符串替换 model.db_table (因为它被引用并且数据库停止识别函数调用)。
如果没有办法用函数替换表,我想知道是否可以从 RawQuerySet 创建 QuerySet (不是最干净的解决方案,但简单的 RawQuerySet 给......一个身体部位带来了如此多的痛苦)。
everybody.
I work with Django 1.3 and Postgres 9.0. I have very complex sql query which extends simple model table lookup with some extra fields. And it wrapped in table function since it is parameterized.
A month before I managed to make it work with the help of raw query but RawQuerySet lacks a lot of features which I really need (filters, count() and clone() methods, chainability).
The idea looks simple. QuerySet lets me to perform this query:
SELECT "table"."field1", ... ,"table"."fieldN" FROM "table"
whereas I need to do this:
SELECT "table"."field1", ... ,"table"."fieldN" FROM proxy(param1, param2)
So the question is: How can I do this? I've already started to create custom manager but can't substitute model.db_table with custom string (because it's being quoted and database stops to recognize the function call).
If there's no way to substitute table with function I would like to know if I can create QuerySet from RawQuerySet (Not the cleanest solution but simple RawQuerySet brings so much pain in... one body part).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您的要求是希望使用原始 SQL 来提高效率,并且仍然可以访问模型方法,那么您真正需要的是一个库来映射 SQL 的哪些字段是哪些模型的列。
该库是 Unjoinify
If your requirement is that you want to use Raw SQL for efficiency purposes and still have access to model methods, what you really need is a library to map what fields of the SQL are the columns of what models.
And that library is, Unjoinify