问题描述:

Suppose I have the following model:

class User(models.Model):

blogs = model.ManyToManyField(Blog)

What is the best way to add a blog to the field for multiple users e.g. I want to add an instance of Blog called blog to all users (i.e. User.object.all()). Do I have to iterate over each result individually or is there a way to do it all at once?

Thanks.

网友答案:

You could do a bulk_create on the through table. For example:

blog = Blog.objects.get(…)
users = User.object.all()

User.blogs.through.objects.bulk_create(
    [User.blogs.through(user_id=user.pk, blog_id=blog.pk) for user in users]
)

That will do one database query.

相关阅读:
Top