3

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?

adkl
  • 634
  • 7
  • 17
  • 1
    I think this has something to do with how the related objects are cached and how bulk_create tries to effeciently create the objects. Here is something thats related https://stackoverflow.com/questions/15933689/how-to-get-primary-keys-of-objects-created-using-django-bulk-create – kevswanberg Jan 23 '18 at 18:22
  • It works for me. Your result is odd. Can you post the results of running `person.posts.all()` in isolation? Can you check that `posts[0].person == person`, and the same for the second item? – dukebody Jan 23 '18 at 19:21
  • @dukebody `person.posts.all()` gives me an empty queryset, but if I go with `person.posts.filter()` I get them all (but from the DB using additional query) – adkl Jan 24 '18 at 10:26
  • Are you using some kind of caching system like cachalot? Sounds like that. `bulk_create` doesn't trigger signal handlers and these caching systems usually rely on them. – dukebody Jan 24 '18 at 14:15
  • No we don't use Cachalot yet. Maybe it's all about a way how a raw SQL is executed in background. Because, as I think, the only thing a database returns after a query is executed is like "N number of rows inserted" and that's it. Django ORM cannot know what are the ids of just inserted rows in that moment. Anyway, thank you for your try to help. – adkl Jan 26 '18 at 23:17
  • Wow, I've just tried the answer from your link @kevswanberg and it works!! Great, thank you! Sorry for my late answer, but I didn't have time to give a try. Cool! – adkl Jan 26 '18 at 23:25

0 Answers0