13๐
โ
You could bulk_create
all the Invoice
objects, refresh them from the db, so that they all have ids, create the Transaction
objects for all the invoices and then also save them with bulk_create
. All of this can be done inside a single transaction.atomic
context.
Also, specifically for django 1.10 and postrgres, look at this answer.
๐คIvan
4๐
You can do it with two bulk create queries, with following method.
new_invoices = []
new_transactions = []
for loop:
invoice = Invoice(params)
new_invoices.append(invoice)
for loop:
transaction = Transaction(params)
transaction.invoice = invoice
new_transactions.append(transaction)
Invoice.objects.bulk_create(new_invoices)
for each in new_transactions:
each.invoice_id = each.invoice.id
Transaction.objects.bulk_create(new_transactions)
๐คSagar Adhikari
- Change default Django REST Framework home page title
- How to prevent "Changed successfully" message when overriding save_model method
- Django Nested Groups: Groups in Groups
0๐
Another way for this purpose can be like the below code snippet:
from django.utils import timezone
from django.db import transaction
new_invoices = []
new_transactions = []
for sth in sth_else:
...
invoice = Invoice(params)
new_invoices.append(invoice)
for sth in sth_else:
...
new_transactions.append(transaction)
with transaction.atomic():
other_invoice_ids = Invoice.objects.values_list('id', flat=True)
now = timezone.now()
Invoice.objects.bulk_create(new_invoices)
new_invoices = Invoice.objects.exclude(id__in=other_invoice_ids).values_list('id', flat=True)
for invoice_id in new_invoices:
transaction = Transaction(params, invoice_id=invoice_id)
new_transactions.append(transaction)
Transaction.objects.bulk_create(new_transactions)
I write this answer based on this post on another question in the community.
๐คJavad
- Django-registration, template
- If I send a python 'Signal' object from a function, what should the "sender" argument be?
- Travis: "Got an error creating the test database: permission denied to create database"
- Filter on datetime closest to the given datetime
- Errno 13 while running docker-compose up
Source:stackexchange.com