为查询集有效地遍历 Django 外键
Traversing Django Foreign Keys efficiently for query sets
我无法有效地获取(二级)相关对象。
我的模型目前看起来像这样
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
中 Account
的 address
列表
prefetch_related
是你的朋友。 https://docs.djangoproject.com/en/1.11/ref/models/querysets/#prefetch-related
处的文档
我无法有效地获取(二级)相关对象。 我的模型目前看起来像这样
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
Account
的 address
列表
prefetch_related
是你的朋友。 https://docs.djangoproject.com/en/1.11/ref/models/querysets/#prefetch-related