2010-07-09 78 views
0

我有以下两种模式检索多对多关系对象的最有效方法是什么?

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'),但它会在我每次访问作者的名字时生成一个查询。

回答

0

我已经找到答案。

在出版物:

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