Django Union从多个数据库查询并以特定格式输出结果

时间:2013-07-16 05:38:14

标签: django django-models django-database

由于我是django的新手,我知道如何在Django中查询单个模型,但我需要同时查询多个模型。

我需要在Django中使用3个模型开发一个UNION查询,即WebQuery,WebReply和BusinessOwners,输出应该是以下形式。

{
    "(#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"
        }]
    },

这是我的models.py文件。

class Businessowners(models.Model):
    b_id = models.IntegerField()
    userid = models.IntegerField(primary_key=True, db_column='UserID')
    email = models.CharField(max_length=150L)
    b_name = models.CharField(max_length=100L)
    class Meta:
        db_table = 'businessowners'

class Users(models.Model):
    user_id = models.BigIntegerField(primary_key=True)
    username = models.CharField(max_length=20L)
    email = models.CharField(max_length=50L)
    date_time = models.DateTimeField()
    class Meta:
        db_table = 'users'

class WebQuery(models.Model):
    query_id = models.BigIntegerField(unique=True)
    conversation_id = models.CharField(max_length=50L)
    u_id = models.CharField(max_length=50L)
    u_query = models.CharField(max_length=500L)
    sent_to = models.CharField(max_length=500L)
    date_time = models.DateTimeField()
    is_reply = models.IntegerField()
    is_responded = models.IntegerField()
    class Meta:
        db_table = 'web_query'

class WebReply(models.Model):
    reply_id = models.IntegerField(primary_key=True)
    query_id = models.BigIntegerField()
    conversation_id = models.CharField(max_length=50L)
    b_id = models.CharField(max_length=20L)
    u_query = models.CharField(max_length=500L)
    user_id = models.CharField(max_length=20L)
    date_time = models.DateTimeField()
    class Meta:
        db_table = 'web_reply'

1 个答案:

答案 0 :(得分:0)

这个问题与另一个问题非常相似,最近有人问我建议你看一下Django Union Query

如果可以收集所有来源,基本上前进的方法是使用SQL视图。然后查询该视图。