I have a large data set of Course objects in a Django application.
courses = Course.objects.all()
I want to make a copy of these courses, except the new courses have different semester values. I have tried this code:
for course in courses:
newCourse = course
newCourse.semester = 'Spring 2012'
newCourse.save()
However, this code is not working. It is just changing the semesters of the current courses.
How do I make a copy of the old data set efficiently? Thank you.
As the documentation on how Django knows whether to update or insert shows, if an object has a primary key value set, Django will always do an update on that object.
So the simple way to clone an object is to set its pk – usually
id– toNone. Then, when you save, Django will create a new object.