【问题标题】:Django ORM - join a lot of tables by user_idDjango ORM - 通过 user_id 加入很多表
【发布时间】:2012-08-06 15:17:19
【问题描述】:

我有大约 5 个带有用户外键的表,即:

class Passport(models.Model):
    user = models.OneToOneField(User)
    ...

此外,像 UserProfile、Company、UserOptions、NotifySettings 等类。我需要为用户摘要页面获取带有连接值的 dict。我还需要加入这个联盟这个汇总统计:

rent_sums = WriteOff.objects.filter(created_at__range=(rent_start, rent_finish), write_off_type='rent').values('user').\
                annotate(rent_amount=Sum('amount')).order_by()

如何在不手动更新结果字典的情况下做到这一点?

【问题讨论】:

    标签: python django join orm


    【解决方案1】:

    您可以通过从 django 执行 custom SQL 来做到这一点,但我在这里看到的主要问题是模型的处理方式,如果您将所有这些用户外键混合到 UserProfile 中会容易得多,例如:

    class UserProfile(models.Model):
        user = fields.OneToOneField(User)
        company = fields.ForeignKey(Company)
        options = fields.ForeignKey(Options)
        notification_settings = fields.ForeignKey(NotifySettings)
        ...
    

    这样你可以更轻松地使用django带来的ORM。在我看来,创建迁移而不是这个庞大的查询会更快。

    【讨论】:

      猜你喜欢
      • 2020-08-04
      • 2014-08-18
      • 2014-08-30
      • 2023-03-22
      • 2014-05-27
      • 2020-02-13
      • 2014-02-11
      • 1970-01-01
      • 2023-02-11
      相关资源
      最近更新 更多