Django copy/paste Queryset

2019-05-31 08:48发布

What is the Django way to copy and paste Queryset except iterating over records and cloning/saving? E.g. a set of records from table A needs to be selected, some field updated and records inserted back to the original table? A sample use case is adding subscribers from mailing list A to mailing list B. Should it be just a loop iterating over QuerySet and cloning/saving record by record, or there is some method for group operation?

3条回答
祖国的老花朵
2楼-- · 2019-05-31 09:15

Django 1.4 has bulk_create method that does his job in 1 sql query

查看更多
家丑人穷心不美
3楼-- · 2019-05-31 09:34

In Django 1.3 the solution is to iterate QuerySet and create copies like this:

from copy import deepcopy
old_obj = deepcopy(obj)
old_obj.id = None
old_obj.save()
查看更多
我只想做你的唯一
4楼-- · 2019-05-31 09:35

It doesn't sound like you want to clone or copy these records - that's something you should avoid in a normalized database anyway.

If you just want to update a single field, then you can do that with the update queryset method:

MyModel.objects.filter(mailing_list=list_a).update(mailing_list=list_b)

If you're talking about adding them to a different M2M relationship, then you can do that simply:

mailing_list_b.users.add(*MyModel.objects.filter(mailing_list=list_a))
查看更多
登录 后发表回答