两个应用程序之间有很多关系。这两个模型是通过另一个模型联系起来的-Pin,所以我可以存储关于这种关系的其他信息。在
我想在Pinboard的DetailView
中显示相关的Note实例。这不是问题所在。但我想预取注释,并在through
表的position
字段上对它们进行排序。在
关于如何归档(预取+在第三个表上排序)有什么提示吗?在
这就是到目前为止我所拥有的……从某种意义上说,它是有效的,我不必为每个条目进行查询,但是我发现如果不对每个实例进行更多的查询,就无法按它们的position
对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)
查看
^{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 %}
我建议你用^{} object 。在
顺便说一下,您根本不需要在
DetailView
上使用prefetch_related
,因为它将导致相同数量的查询。在另外,since you're already fetching the ^{} 我建议你用}。在
{% if pinboard.notes.all %}
代替{相关问题 更多 >
编程相关推荐