How to Save a Query Set of Objects in a Single Transaction without using a for loop in Django ORM

Just a quick question, for ex, posts variable has n objects, and i need to save the post id in a post_tag model, how can i achieve without using a for loop, and just with the a single transaction using Django ORM.

Here is a small snippet what i want to achieve:

posts = Post_Tag.objects.filter(tag_id = subcat).values_list('post_id', flat = True)
for post in posts:
   post_home_feed = Post_Home_Feed.objects.create(post_id = post.post_id, user_id = user_id.id)

Any leads much appreciated, Thanks in advance.

Upvotes: 1

Views: 155

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477684

The for loop is not the problem, the problem is that you make n trips to the database for n objects. You can create objects in bulk with .bulk_create(…) [Django-doc]:

posts = Post_Tag.objects.filter(tag_id=subcat).values_list('post_id', flat=True)

data = [
    Post_Home_Feed(post_id=post.post_id, user_id=user_id.id)
    for post in posts
]
Post_Home_Feed.objects.bulk_create(data)

This will thus make Post_Home_Feed objects in memory and then create records for all these objects with a single trip to the database.


Note: Models in Django are written in PascalCase, not snake_case, so you might want to rename the model from Post_Home_Feed to PostHomeFeed.

Upvotes: 1

Related Questions