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

1👍

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.

Leave a comment