2017-08-14 79 views
1

我很难高效地获取(二级)相关对象。 我的模型是目前这个样子为查询集有效地遍历Django外键

class Transaction(models.Model): 
    from_account = models.ForeignKey(Account, related_name="sent") 
    to_account = models.ForeignKey(Account, related_name="recieved") 
    ... 

class Account(models.Model): 
    address = models.CharField(max_length=42, primary_key=True) 
    ... 

我一直在做,到目前为止获得的transaced_with的汇总清单的帐户如下:

accs = [] 
if hasattr(account, 'recieved'): 
    for tx in account.recieved.all(): 
     acc = tx.from_account 
     accs.append(acc) 

if hasattr(account, 'sent'): 
    for tx in account.sent.all(): 
     acc = tx.to_account 
     accs.append(acc) 
return accs 

这样,但是速度很慢,所以我在想, 聚合这类相关对象的有效方法是什么?我最想要的是address列表Account中的accs

回答