【问题标题】:Django ORM equivalentDjango ORM 等价物
【发布时间】:2010-11-07 02:36:52
【问题描述】:

我在视图中有以下代码来获取要显示的帐户的一些信息。我尝试了几个小时通过 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))

【问题讨论】:

  • 发布您的模型,我们不必猜测
  • 不用单独回答谢谢,呵呵。只要接受他的答案作为正确的答案。

标签: sql django orm models


【解决方案1】:

如果您发布模型会更容易。但从 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

【讨论】:

    猜你喜欢
    • 2015-02-06
    • 2018-07-02
    • 2016-12-07
    • 1970-01-01
    • 2017-11-22
    • 2010-11-17
    • 2021-08-24
    • 2012-02-18
    • 2019-05-18
    相关资源
    最近更新 更多