Django ORM相当于

时间:2009-06-30 18:43:07

标签: sql django orm models

我在视图中有以下代码,以获取有关要显示的帐户的一些信息。我试了几个小时才能通过ORM让它工作,但无法使它工作。我最终在原始SQL中完成它,但我想要的并不是很复杂。我确信可以使用ORM。

最后,我只想从几个表中填充字典accountDetails。

cursor.execute("SELECT a.hostname, a.distro, b.location FROM xenpanel_subscription a, xenpanel_hardwarenode b WHERE a.node_id = b.id AND customer_id = %s", [request.user.id])
accountDetails = {
    'username': request.user.username,
    'hostname': [],
    'distro': [],
    'location': [],
}

for row in cursor.fetchall():
    accountDetails['hostname'].append(row[0])
    accountDetails['distro'].append(row[1])
    accountDetails['location'].append(row[2])

return render_to_response('account.html', accountDetails, context_instance=RequestContext(request))

1 个答案:

答案 0 :(得分:2)

如果发布模型会更容易。但是从SQL我假设模型是这样的:

class XenPanelSubscription(models.Model):
    hostname = models.CharField()
    distro = models.CharField()
    node = models.ForeignKey(XenPanelHardwareNode)
    customer_id = models.IntegerField()

    class Meta:
        db_table = u'xenpanel_subscription'

class XenPanelHardwareNode(models.Model):
    location = models.CharField()

    class Meta:
        db_table = u'xenpanel_hardwarenode'

基于这些模型:

accountDetails = XenPanelSubscription.objects.filter(customer_id = request.user.id)
for accountDetail in accountDetails:
    print accountDetail.hostname, accountDetail.distro, accountDetail.node.location