Django 4.1: implementing Bulk Create and Auto-incrementing IDs in Related Models
I'm working through a tutorial and I'm working with an scenario while trying to bulk create instances of a model with a foreign key relationship in Django 4.1. When using `bulk_create` to insert records into the main model, the related model's auto-incrementing IDs are not being generated as I expect. Hereβs a simplified example of my models: ```python from django.db import models class Author(models.Model): name = models.CharField(max_length=100) class Book(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(Author, on_delete=models.CASCADE) ``` I have a list of authors and I'm trying to create multiple books for each author using the following code: ```python authors = [Author(name='Author 1'), Author(name='Author 2')] Author.objects.bulk_create(authors) books = [Book(title='Book 1', author=authors[0]), Book(title='Book 2', author=authors[1])] Book.objects.bulk_create(books) ``` The scenario arises when I attempt to access the `id` of the `author` after the authors are created. The `Author` instances seem to have `id` attributes that aren't set or are incorrect when I pass them to the `Book` instances. I get an behavior that states: ``` IntegrityError: NOT NULL constraint failed: myapp_book.author_id ``` I've checked that the authors are being saved properly, and they do get IDs assigned when I create them individually. My understanding is that `bulk_create` does not populate the primary key field of the instances after the records are created. I tried using `refresh_from_db()` after the bulk create but it throws an behavior since `bulk_create` doesn't return the created objects. Is there a way to resolve this or a recommended approach to handle this scenario without resorting to saving each author individually? Any insights would be greatly appreciated! For context: I'm using Python on Linux. Is there a better approach? What's the best practice here? I'm open to any suggestions.