Django联盟查询 [英] Django Union Query
问题描述
我需要在Django中开发一个UNION查询,其中有3个模型,即WebQuery,WebReply和BusinessOwners,输出应该是下面的形式。
code $ {
(#conversation_id#)_(#b_id#):{
from:(#user_id),
email #
date_time:#从db,
查询:你是否打开?,
from_r_id:(#representative_id)
from_r_name:(#rep_name),
business_registered:FALSE
to_business_name:CCD saket,
chat:[{
direction:1,
text:yes sir,
date_time:424 577
},{
direction:0 ,
text:ok,
date_time:424 577
}]
},
pre>
我知道如何查询当只涉及一个模型,但不能确定联合查询。
这将如何实现?解决方案我个人会说,如果这将是一个常见的查询我建议做一个SQL View然后查询。
w3schools对一个视图有一个非常简单的概述: http://www.w3schools.com/sql/sql_view.asp
在SQL中,视图是基于SQL语句结果集的虚拟表。
这意味着您可以编写所需的sql语句并使用此命令创建视图。然后创建一个镜像该视图的django模型,然后您可以使用它查询。
所以,您将创建一个SQL视图:
CREATE VIEW view_name AS
SELECT a,b,c
FROM table_name
WHERE条件
然后创建一个django模型,与一个正常的模型略有不同:
class view_name(models.Model):
class Meta:
#https://docs.djangoproject.com/en/1.5/ref/models/options/ #django.db.models.Options.managed
managed = False
a = models.CharField(max_length)
....
managed = false
> https://docs.djangoproject.com/en/1.5/ref/models/选项/#django.db.models.Options.managed
然后,您可以使用规范来查询或者还有类似的问题:
上一个stackoverflow问题,django orm中的union
I need to develop a UNION query in Django with 3 models namely WebQuery,WebReply and BusinessOwners and the output should be of the form below.
{ "(#conversation_id#)_(#b_id#)": { "from": "(#user_id)", "email": "(#user_email)", "date_time": "#get from db", "query": "are you open ?", "from_r_id": "(#representative_id)", "from_r_name": "(#rep_name)", "business_registered": "FALSE" "to_business_name": "CCD saket", "chat": [{ "direction": 1, "text": "yes sir", "date_time": "424 577" }, { "direction": 0, "text": "ok", "date_time": "424 577" }] },
I know how to query when only one model is involved, but not sure of the union query. How will this be achieved?
解决方案I personally would say that if this is going to be a common query then I would recommend making a SQL View then querying that.
w3schools has a VERY simple overview of what a view is : http://www.w3schools.com/sql/sql_view.asp
In SQL, a view is a virtual table based on the result-set of an SQL statement.
This means you can write your required sql statement and create a view using this. Then create a django model which mirrors that view which you can then use to query.
So, you will create an SQL view:
CREATE VIEW view_name AS SELECT a, b, c FROM table_name WHERE condition
Then create a django model, which has a slight difference to a normal model:
class view_name(models.Model): class Meta: # https://docs.djangoproject.com/en/1.5/ref/models/options/#django.db.models.Options.managed managed = False a = models.CharField(max_length) ....
managed = false
> https://docs.djangoproject.com/en/1.5/ref/models/options/#django.db.models.Options.managedYou can then query this using the normal django orm syntax
Or there is similar questions:
Previous stackoverflow question, union in django orm
How can I find the union of two Django querysets?
这篇关于Django联盟查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!