【问题标题】:Django: Join multiple models on a field value for use in a Django templateDjango:在一个字段值上加入多个模型以在 Django 模板中使用
【发布时间】:2019-01-19 13:33:07
【问题描述】:

我正在使用 Django 2.0。我有多个模型共享一个共同的领域,并试图找到相关的对象。示意性地,给定模型 Model1 和 Model2,对于 QuerySet 中的每个 Model1,我们希望找到对应的 Model2 对象,使得

Model1.property == Model2.property. 

在这个应用程序中,最多有一个,但可能没有,满足这个条件的 Model2。此 QuerySet 将在 Django 模板中用于显示结果。

现在,我对如何解决这个问题有几个想法,但我想知道是否有标准解决方案。

注意事项:我知道 Django 模板语言没有内置方法来查找具有特定属性值的对象

想法:

1) 模板中的 For 循环。遍历 Model2,评估 Model2.property 并测试 Model2.property == Model1.property。如果为真,则存储 Model2。看起来很笨重,并且违背了 Django 模板语言的理念。

2) 在 python 中处理它。或许将一个新属性附加到 Model1

Model1.property.model2 = Model2.objects.filter(property=property)

或使用带有“get”的 try/expect 块

3) 在查询中处理它。或许用相关的 Model2 标注检索 Model1 的查询集的结果

4) 是否可以使用自定义模板标签将此功能添加到 Django 模板中?

这是我的模型,供参考:

class ModuleSubscription(models.Model):
subscriber = models.ForeignKey(User, on_delete=models.CASCADE)  # owner of module
module = models.ForeignKey(Module, on_delete=models.CASCADE)  # id of owned module


class ModuleAssignment(models.Model):
delegation = models.ForeignKey(Delegation, on_delete=models.CASCADE)
module = models.ForeignKey(Module, on_delete=models.CASCADE)  # assigned module
access_granted = models.BooleanField(default=False)
module_log = models.ForeignKey(ModuleLog, default=None, on_delete=models.SET_DEFAULT, null=True)

现在,我需要按订阅者过滤 ModuleSubscription 和通过委托过滤 ModuleAssignment,然后找到生成的 ModuleSubscription.module == ModuleAssignment.module 的位置。原因是,对于每个 ModuleSubscription,我需要相应 ModuleAssignment 中的 access_granted 属性(如果存在)。然后,在模板中,我需要遍历所有过滤的 ModuleSubscriptions 并显示关联的 ModuleAssignment.access_granted

【问题讨论】:

  • 你为什么不发布你的模型代码;因为如果它们是相关的,您应该在模型中使用 ForeignKey 或其他相关字段,这样可以快速找到相关项目!
  • 将模型添加到原始帖子
  • 这听起来像是一个糟糕的设计,感觉像是一个 XY 问题。我建议你拿一张纸,在上面写下一些示例数据,然后按照你的想法去做。将您的假设应用于真实数据。通过理解、调试和故障排除性能实现复杂性和可能的​​问题。可能你会想出一些其他模型架构和一些看起来像 ModuleGrants (user, module, is_granted) 的实体。
  • 感谢您的建议。您描述的表是 ModuleAssignment 表。委托表包含用户数据,所以 ModuleAssignment 基本上是 (user, model, is_granted)。仅使用 ModuleAssignment 表的问题在于,您需要根据 ModuleSubscription 中的对象进行过滤。反过来几乎是同样的问题。

标签: python django django-models django-templates


【解决方案1】:

(除了我的评论)我说的是所有赠款都将公开的表格。可能我误解了delegation 在这里应该是什么意思。

# filtering part
modules = ModuleSubscription.objects.filter(subscriber=_s)
grants = ModuleAssignment.objects.filter(delegation=_d, module__in=modules)

# template part
for g in grants:
  ...

是吗?

【讨论】:

    猜你喜欢
    • 2017-01-10
    • 2019-09-20
    • 2020-01-19
    • 2013-10-23
    • 1970-01-01
    • 2017-11-02
    • 2012-02-05
    • 2018-05-03
    • 2011-07-03
    相关资源
    最近更新 更多