Django copy/paste Queryset

瘦欲@ 提交于 2019-12-08 05:32:08

问题


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?


回答1:


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




回答2:


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))



回答3:


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()


来源:https://stackoverflow.com/questions/10911416/django-copy-paste-queryset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!