当前位置: 动力学知识库 > 问答 > 编程问答 >

python - Django add into many-to-many field for each item in a queryset?

问题描述:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: