【问题标题】:What is the most db efficient way to get specific fields of a foreign key in a queryset using Wagtail page models使用 Wagtail 页面模型在查询集中获取外键的特定字段的最高效的方法是什么
【发布时间】:2019-04-29 11:52:01
【问题描述】:

所以我有这个模型:

class FieldPosition(Orderable):
    page = ParentalKey('PlayerDetailPage', on_delete=models.CASCADE, related_name='field_position_relationship')
    field_position = models.CharField(verbose_name=_('Field position'), max_length=3, choices=FIELD_POSITION_CHOICES, null=True)

还有这个 Wagtail 页面模型:

class PlayerDetailPage(Page):

    content_panels = [ InlinePanel('field_position_relationship', label=_('Field position'), max_num=3), ]

我在页面模型中做了一个属性:

@property
def position(self):
    position = [
        n.field_position for n in self.field_position_relationship.all()
        ]
        return position

所以我可以通过以下方式访问模板中的field_position

{% for p in  page.position %}
{{ p }}
{% endfor %}

但是有没有更好的方法来做到这一点?我觉得我对数据库的访问太多了,而且我有很多查询。我更喜欢这样的东西: PlayerDetailPage.objects.values('field_position_relationship__field_position')

然后我得到 all PlayerDetailPage entries 的值,我只想要正在显示的特定页面的值。我怎样才能实现这样的目标?

【问题讨论】:

    标签: django django-views wagtail


    【解决方案1】:

    您所追求的可能是这样的。这是您的两个答案的组合。

    @property
    def position(self):
        return self.field_position_relationship.values('field_position')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-12
      • 2011-11-13
      • 2015-05-10
      • 1970-01-01
      • 2020-10-16
      • 2017-04-22
      • 2016-09-25
      • 1970-01-01
      相关资源
      最近更新 更多