python - Traversing Django Foreign Keys efficiently for query sets -
i'm having trouble efficiently getting (second degree) related objects. models
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) ...
what have been doing far aggregated list of transaced_with
account follows:
accs = [] if hasattr(account, 'recieved'): tx in account.recieved.all(): acc = tx.from_account accs.append(acc) if hasattr(account, 'sent'): tx in account.sent.all(): acc = tx.to_account accs.append(acc) return accs
this way slow, wondering, the efficient way aggregate these sort of related objects? want in end list of address
account
s in accs
prefetch_related
friend here. documentation @ https://docs.djangoproject.com/en/1.11/ref/models/querysets/#prefetch-related
Comments
Post a Comment