如何根据Django中M2M关系的“through”表中的字段进行排序?

2024-05-13 00:40:49 发布

您现在位置:Python中文网/ 问答频道 /正文

两个应用程序之间有很多关系。这两个模型是通过另一个模型联系起来的-Pin,所以我可以存储关于这种关系的其他信息。在

我想在Pinboard的DetailView中显示相关的Note实例。这不是问题所在。但我想预取注释,并在through表的position字段上对它们进行排序。在

关于如何归档(预取+在第三个表上排序)有什么提示吗?在

示例

这就是到目前为止我所拥有的……从某种意义上说,它是有效的,我不必为每个条目进行查询,但是我发现如果不对每个实例进行更多的查询,就无法按它们的positionNote实例进行排序。在

型号

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)

查看

^{pr2}$

模板

{% 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 %}

Tags: 实例model排序titlemodelspinpositioncontent
1条回答
网友
1楼 · 发布于 2024-05-13 00:40:49

我建议你用^{} 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 ^{}我建议你用{% if pinboard.notes.all %}代替{}。在

相关问题 更多 >