检索多对多关系对象的最有效方法是什么?

时间:2010-07-09 03:23:04

标签: django many-to-many

我有以下两个模型

class Author(Model):
    name = CharField()

class Publication(Model):
    title = CharField()

我使用中间表来跟踪作者列表。作者的顺序很重要;这就是为什么我不使用Django的ManyToManyField。

class PubAuthor(Model):
    author = models.ForeignKey(Author)
    pubentry = models.ForeignKey(Publication)
    position = models.IntegerField(max_length=3)

问题是,鉴于出版物,获得所有作者出版的最有效方法是什么?

我可以使用pubentry.pubauthor_set.select_related()。order_by('position'),但是每次访问作者姓名时都会生成一个查询。

1 个答案:

答案 0 :(得分:0)

我找到了答案。

在出版物中:

    def authors(self):
        return Author.objects.all().filter(
            pubauthor__pubentry__id=self.id).order_by('pubauthor__position')