开发者

What's the most efficient way to retrieve objects of many-to-many relationships?

I have the following two models

class Author(Model):
    name = CharField()

class Publication(Model):
    title = CharField()

And I use an intermediary table to keep track of开发者_StackOverflow社区 the list of authors. The ordering of authors matter; and that's why I don't use Django's ManyToManyField.

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

The problem is, given a publication, what's the most efficient way to get all authors for the publication?

I can use pubentry.pubauthor_set.select_related().order_by('position'), but then it this will generate one query each time I access the author's name.


I've found out the answer.

In publications:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜