[英]How to fastly update field from a related model in django
I wanted to update a few milion records with a value from a related record using Django queryset but I got stuck on我想使用 Django 查询集使用相关记录中的值更新几百万条记录,但我陷入了困境
django.core.exceptions.FieldError: Joined field references are not permitted in this query
Before I did it with a Subquery
, but it was too slow.在我使用
Subquery
之前,它太慢了。
All I want is to execute this simple query, but wasn't able to find a Queryset equivalent for it, so I had to go with raw SQL.我想要的只是执行这个简单的查询,但找不到与之等效的查询集,所以我不得不用原始的 SQL 来 go。
update card_cardtransaction
set clearing_date = api_invoice.date_activated
from card_cardtransaction ct join api_invoice
on ct.invoice_id = api_invoice.id
where ct.date_created > '2022-05-17' and id in %ids
Any ideas how to compose this query using only queryset methods?任何想法如何仅使用查询集方法来编写此查询?
This is the closest I was able to come with, but still with the error above.这是我能想到的最接近的,但仍然存在上述错误。
CardTransaction.objects.filter(id__in=ids)
.select_related('invoice')
.update(
clearing_date=F("invoice__date_activated")
)
Bulk update could be worth a try:批量更新可能值得一试:
card_transactions = CardTransaction.objects.filter(id__in=ids).select_related('invoice')
cts = []
for ct in cart_transactions:
ct.clearing_date = ct.invoice.date_activated
cts.append(ct)
CardTransactions.objects.bulk_update(cts, ['clearing_date'], batch_size=1000)
see the django docs for more有关更多信息,请参阅django 文档
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.