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.core.exceptions.FieldError: Joined field references are not permitted in this query

Before I did it with a Subquery, but it was too slow.

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.

update card_cardtransaction
set clearing_date = api_invoice.date_activated
from card_cardtransaction ct join api_invoice
                               on ct.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.


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
CardTransactions.objects.bulk_update(cts, ['clearing_date'], batch_size=1000)

see the django docs for more

Back to Top