有效地遍历Django外键用于查询集

时间:2017-08-14 23:55:05

标签: python django django-models django-queryset django-orm

我无法有效地获得(第二学位)相关对象。 我的模特目前看起来像这样

.gradient-text {
  color: #00e1ff;
}
@supports (mix-blend-mode: lighten) {
  .gradient-text {
    display: inline-block;
    position: relative;
    color: #fff;
    background: #000;
    mix-blend-mode: lighten;
  }
 .gradient-text::before {
    content: '';
    display: block;
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background: -webkit-linear-gradient(120deg,#00e1ff, #ffeb50);
    background: linear-gradient(120deg,#00e1ff, #ffeb50);
    pointer-events: none;
    mix-blend-mode: multiply;

  }
}


/* Page styling, ignore */
body {
  margin: 0;
  font-family: "Lato", sans-serif;
  text-align: center;
}

.originals {
  background: #0C2322;
  min-height: 50vh;
  padding: 2em;
}

h3 {
  font-size: 2em;
  margin: 0.5em;
  opacity: 0.9;
}

到目前为止,我一直在为帐户获取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的{​​{1}}列表

1 个答案:

答案 0 :(得分:0)