Django 左连接
我有一些左连接问题。我有以下模型,
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 左连接到它(如果有)。
现在我正在用原始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()
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
I need to grab all the server instances and left join the CommandInfo to it if there is one.
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()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用如下代码:
这将返回所有将
s
设置为外键的 CommandInfo 对象的列表。您可以在 Django 文档中获取更多信息,“向后跟踪关系”。
You can use code like the following:
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 ORM 需要使用 select_lated() 显式命名左连接字段名称。
这只是我的想法,所以你可能需要调整它,但尝试如下:
Sometimes the Django ORM needs the left join field name to be explicitly name with select_related().
This is just off the top of my head so you'll probably need to tweak it, but try something like:
请注意,您需要获取服务器列表,因为您可以使用没有 CommandInfo 的服务器
Please note that you need to get the servers list due you can servers without CommandInfo