我有一个模型,其中一个字段是ForeignKey,这样每个子对象都链接到父对象。
在我的(jinja2)模板中,我列出了子模型中对象子集的一些属性,包括父项的属性之一。该页面加载非常缓慢,所以我想知道是否有更快的方法可以执行以下操作:
views.py
class TransactionView(LoginRequiredMixin, ListView):
model = Transactions
context_object_name = 'transaction_list'
template_name = 'bank/transactions.html'
def get_queryset(self):
return Transactions.objects.filter(owner_id=self.request.user)
template.html
<tbody>
{% for transaction in transaction_list %}
<tr>
<td>{{transaction.source_document.service_provider}}</td>
<td>{{transaction.account}}</td>
<td>{{transaction.tnsx_date}}</td>
<td>{{transaction.end_bal}}</td>
<td>{{transaction.amount}}</td>
<td>{{transaction.category}}</td>
</tr>
{% endfor %}
</tbody>
models.py
class Transactions(models.Model):
def __str__(self):
return str(self.tnsx_uuid)
owner = models.ForeignKey(
User,
on_delete=models.CASCADE,
db_index=True,
editable=True,
)
source_document = models.ForeignKey(
Document,
on_delete=models.CASCADE,
editable=True,
)
tnsx_uuid = models.UUIDField(default=uuid.uuid4, unique=True)
account = IBANField(enforce_database_constraint=True)
currency = models.CharField(max_length=4, blank=False, null=False)
currency_assumed = models.BooleanField(null=False)
<etc>
答案 0 :(得分:0)
如iklinac所建议的那样,使用.prefetch_related()
可以大大提高查询速度。
将views.py
更改为以下内容:
class TransactionView(LoginRequiredMixin, ListView):
model = Transactions
context_object_name = 'transaction_list'
template_name = 'bank/transactions.html'
def get_queryset(self):
return Transactions.objects.filter(owner_id=self.request.user).prefetch_related('source_document')