Django Union Query

瘦欲@ 提交于 2019-12-31 04:21:10

问题


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?


回答1:


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.managed

You 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?




回答2:


How can I find the union of two Django querysets? provides an example of a union using the '|' operator. I'm not sure how different your models are. If there's common fields you could place those in a separate model and use model inheritance



来源:https://stackoverflow.com/questions/17653743/django-union-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!