2010-07-09 49 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') 
相關問題