django LEFT JOIN不是本机数据库

时间:2014-01-24 02:58:36

标签: django

我有数据库,我将与django集成,我已经有模型,我将执行一些JOIN LEFT查询django方式。

这是我的模特:

class Platforms(models.Model):
    id = models.IntegerField(primary_key=True)
    name = models.CharField(max_length=64)
    prefix = models.CharField(max_length=2)

    class Meta:
        managed = False
        db_table = 'lu_platform'

    def __unicode__(self):
        return self.name

class Sources(models.Model):
    id = models.IntegerField(primary_key=True)
    name = models.CharField(max_length=32)

    class Meta:
        managed = False
        db_table = 'lu_sourcetype'

    def __unicode__(self):
        return self.name

class Events(models.Model):
    id = models.IntegerField(primary_key=True)
    platform_id = models.IntegerField()
    host_id = models.IntegerField()
    sourcetype_id = models.IntegerField()
    event_datetime = models.DateTimeField(auto_now=True)
    data = models.CharField(max_length=2048)

    class Meta:
        managed = False
        db_table = 'event'

这是我的查询,如何以django方式执行以下查询?

SELECT event_datetime, lu_platform.name, host.name, data 
FROM event 
LEFT JOIN lu_platform ON event.platform_id = lu_platform.id 
LEFT JOIN host ON event.host_id = host.id
WHERE event.platform_id = 8 
AND event_datetime BETWEEN '2013-11-23' AND '2013-12-28' 
AND event.sourcetype_id = 1

1 个答案:

答案 0 :(得分:1)

首先,需要更改模型以提及ForeignKey关系。接下来,Django自动添加id字段并且是多余的。最后,建议对模型使用单数名称。我会用这种方式设计它们:

class Platform(models.Model):
    name = models.CharField(max_length=64)
    prefix = models.CharField(max_length=2)

    class Meta:
        managed = False
        db_table = 'lu_platform'

    def __unicode__(self):
        return self.name

class Source(models.Model):
    name = models.CharField(max_length=32)

    class Meta:
        managed = False
        db_table = 'lu_sourcetype'

    def __unicode__(self):
        return self.name

class Event(models.Model):
    host_id = models.IntegerField()
    platform = models.ForeignKey(Platform)
    sourcetype = models.ForeignKey(Source)
    event_datetime = models.DateTimeField(auto_now=True)
    data = models.CharField(max_length=2048)

    class Meta:
        managed = False
        db_table = 'event'

最后,查询看起来像这样:

Event.objects.filter(platform__id=8, event_datetime__range=["2013-11-23", "2013-12-28"],sourcetype_id=1).values(
      "event_datetime", "platform__name", "host_id", "data")

我在火车上,所以我无法验证上面的代码,但它应该有用。