django左加入 [英] django left join
本文介绍了django左加入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一些左联接问题..我有以下模型
I have a bit of a left join issue.. I have the following models
class CommandInfo(models.Model):
server = models.ForeignKey(Server)
count = models.IntegerField(default=1)
ts = models.DateTimeField(auto_now=True)
class Server(models.Model):
name = models.CharField(max_length=100)
group = models.ForeignKey(ApplicationGroup, blank=True, default=0)
host = models.CharField(max_length=100)
ip = models.IPAddressField(db_index=True)
about = models.TextField()
firstTS = models.DateTimeField(auto_now_add=True)
lastTS = models.DateTimeField(auto_now=True)
processed = models.SmallIntegerField(max_length=1, default=0)
def __unicode__(self):
return self.host
我需要获取所有服务器实例,如果有的话,将CommandInfo加入其中.
I need to grab all the server instances and left join the CommandInfo to it if there is one.
现在我正在原始sql中完成
Right now I'm doing it in raw sql
from django.db import connection
cursor = connection.cursor()
cursor.execute("SELECT host,ts,count as host FROM servers_server LEFT JOIN cmds_commandinfo ON server_id=servers_server.id")
servers = cursor.fetchall()
推荐答案
您可以使用以下代码:
s = Server.objects.get(id=1)
cmdinfo = s.commandinfo_set.all()
这将返回所有已将s
设置为外键的CommandInfo对象的列表.
Which would return a list of all CommandInfo objects that have s
set as the foreign key.
You can get more info at the Django docs, "Following Relationships Backward".
这篇关于django左加入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文