1

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?

Praful Bagai
  • 16,684
  • 50
  • 136
  • 267
  • can you show us the backend code you are looking to do the union on? And show us the code you have tried so far – karthikr Jul 15 '13 at 14:01
  • @karthikr - Here is the link to my models.py file. Kindly review and provide the necessary help. Thanks :) [http://stackoverflow.com/questions/17651815/database-error-no-such-table-django/17653647?noredirect=1#17653647] – Praful Bagai Jul 15 '13 at 15:47

2 Answers2

0

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?

Community
  • 1
  • 1
Matt Seymour
  • 8,880
  • 7
  • 60
  • 101
0

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

jocassid
  • 4,429
  • 1
  • 13
  • 6