I have a problem with accessing bulk inserted one-to-many relationship objects using bulk_create
. Here is my code:
My models:
class Person(models.Model):
# ... other fields
class Post(models.Model):
person = models.ForeignKey(to=Person, related_name="posts")
text = models.CharField(max_length=100)
# ... other fields
Now I want to insert thousands of posts for a person. I'm doing it as follows:
person = Person(foo="bar")
person.save()
posts = [Post(person=person, text="post1"), Post(person=person, text="post2")]
person.posts.bulk_create(posts)
# Now I want to have an access to the person.posts and pass it to a serializer
return PostSerializer(person.posts.all(), many=True).data
When I execute, it doesn't populate the relationship => it's empty. I want to perform this without additional query to the database. Is that possible?