如何通过`to`表中的字段为Django中的M2M关系订购?

时间:2016-02-15 13:37:34

标签: python django m2m

我有两个模型 - 注意 Pinboard - 在Django应用程序中有多对多的关系。这两个模型通过另一个模型 - Pin 相关 - 所以我可以存储关于这种关系的其他信息。

我想在 Pinboard DetailView中显示相关的 Note 实例。那不是问题。但我希望预取备注,并在position表的through字段中订购

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

实施例

这就是我到目前为止......它在某种意义上是有效的,我不必查询每个条目,但是我发现没有办法按它们的{{{em> Note 实例来命令它们1}}没有针对每个实例的更多查询。

模型

position

查看

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')

1 个答案:

答案 0 :(得分:3)

我建议您使用Prefetch object

$result = array('D','P','X','M');

顺便说一句,您不需要在class PinboardDetailView(DetailView): model = Pinboard queryset = Pinboard.objects.prefetch_related( Prefetch( 'notes', Note.objects.order_by('pinboard_pins__position'), ) ) 上使用prefetch_related因为它会产生相同数量的查询。

另外,since you're already fetching the pinboard.notes我建议您使用DetailView代替{% if pinboard.notes.all %}