【问题标题】:A simple database inner join using django使用 django 的简单数据库内部连接
【发布时间】:2014-03-21 10:47:19
【问题描述】:

我有两个来自旧数据库的表,使用 inspectdb 导入到我的 django 应用程序

这是我的模型定义

class AppCosts(models.Model):
    cost = models.DecimalField(max_digits=10, decimal_places=2)


class AppDefinitions(models.Model):
    data = models.TextField()
    permissions = models.CharField(max_length=50, blank=True)
    appcost=models.OneToOneField(AppCosts, db_column='id')

AppDefinitions 中的每个应用程序在 AppCosts 中都有一个条目 - 一对一的关系

当我使用 select_related() 时,我得到:

>>> AppDefinitions.objects.select_related().query.__str__()

    u'SELECT _app_definitions.id, _app_definitions.data,
  _app_definitions.permissions, _app_definitions.id, _app_costs.id, 
  _app_costs.cost FROM _app_definitions INNER JOIN _app_costs 
  ON ( _app_definitions.id = _app_costs.id )'

>>> a = AppDefinitions.objects.select_related().first()

>>> a.id
u'abaqus'

>>> a.cost
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'AppDefinitions' object has no attribute 'cost'

>>> a.appcost
<AppCosts: abaqus,1.50>    

>>> a.appcost.cost
Decimal('1.50')

现在有两个问题:

  • 查询从两个字段中提取 id 两次(没什么大不了的,因为该表最多不会有超过几百个条目,但我仍然希望它是正确的)
  • 我必须以 x.appcost.cost 的形式访问成本,而不是简单的 x.cost

我如何做到这一点?

我不愿意使用自定义 SQL,因为这首先会破坏使用 django 的 ORM 的目的。

【问题讨论】:

    标签: python django orm


    【解决方案1】:

    你说你想使用 Django 的 ORM,然后说你想做一些与之截然相反的事情,即以x.cost 访问成本。

    Django 不会让你这样做,因为它完全破坏了对象模型。 cost 是 AppCosts 模型的属性,而不是 Costs 模型。如果它真的让您感到困扰,您可以在 Costs 上添加一个 property,它返回 self.appcosts.cost,只要您不尝试在查询中使用它,它就会做您想做的事情。 p>

    【讨论】:

    • 谢谢 - 这是有道理的。
    猜你喜欢
    • 2013-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-12
    相关资源
    最近更新 更多