【发布时间】:2018-01-22 21:24:41
【问题描述】:
我无法有效地获取(二级)相关对象。 我的模型目前看起来像这样
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
但是这种方式很慢,所以我想知道,
聚合这些相关对象的有效方法是什么?我最终想要的是accs中Accounts中的address列表
【问题讨论】:
标签: python django django-models django-queryset django-orm