【发布时间】:2016-02-15 13:37:34
【问题描述】:
我有两个模型 - Note 和 Pinboard - 在 Django 应用程序中具有多对多关系。这两个模型通过另一个模型(Pin)相互关联,因此我可以存储有关该关系的其他信息。
我想在 Pinboard 的 DetailView 中显示相关的 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 %}
【问题讨论】: