【问题标题】:How to order by a field from the `through` table for a M2M relationship in Django?如何按 Django 中 M2M 关系的“通过”表中的字段排序?
【发布时间】:2016-02-15 13:37:34
【问题描述】:

我有两个模型 - NotePinboard - 在 Django 应用程序中具有多对多关系。这两个模型通过另一个模型(Pin)相互关联,因此我可以存储有关该关系的其他信息。

我想在 PinboardDetailView 中显示相关的 Note 实例。那不是问题。但我想预取笔记并在through表的position字段中订购它们。

关于如何存档的任何提示(预取 + 在第三张表上排序)?

示例

这是我目前所拥有的……它在某种意义上是有效的,我不必查询每个条目,但我发现无法通过 @987654324 对 Note 实例进行排序@ 无需对每个实例进行更多查询。

模型

from django.db import models


class Note(models.Model):

    title = models.CharField(max_lenght=200)

    content = models.TextField()


class Pinboard(models.Model):

    title = models.CharField(max_lenght=200)

    notes = models.ManyToManyField(
        Note, blank=True, related_name='pinboards', through='Pin'
    )


class Pin(models.Model):

    class Meta:
        ordering = ['position', ]
        get_latest_by = 'position'

    pinboard = models.ForeignKey(Pinboard, related_name='note_pins')

    note = models.ForeignKey(Note, related_name='pinboard_pins')

    position = models.PositiveSmallIntegerField(default=0)

查看

from django.views.generic import DetailView


class PinboardDetailView(DetailView):

  model = Pinboard

  queryset = Pinboard.objects.prefetch_related('notes')

模板

{% extends 'base.html' %}
{% block content %}
<h1>{{ pinboard.title }}</h1>
{% if pinboard.notes.all.exists %}
    <ol>
    {% for note in pinboard.notes %}
        <li>{{ note.title }}</li>
    {% endfor %}
    </ol>
{% else %}
    <p>Nothing here yet…</p>
{% endif %}
{% endblock content %}

【问题讨论】:

    标签: python django m2m


    【解决方案1】:

    我建议你使用Prefetch object

    class PinboardDetailView(DetailView):
        model = Pinboard
        queryset = Pinboard.objects.prefetch_related(
            Prefetch(
                'notes',
                Note.objects.order_by('pinboard_pins__position'),
            )
        )
    

    顺便说一句,您根本不需要在 DetailView 上使用 prefetch_related,因为它会产生相同数量的查询。

    另外,since you're already fetching the pinboard.notes 我建议你使用{% if pinboard.notes.all %} 而不是{% if pinboard.notes.all.exists %}

    【讨论】:

    猜你喜欢
    • 2016-05-07
    • 1970-01-01
    • 2013-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-13
    • 2021-01-15
    • 1970-01-01
    相关资源
    最近更新 更多