Copy or clone an object instance in Django/Python

I've following scenario:

class CourseTemplate(models.Model):
    title = models.CharField(max_length=70)
    teacher = models.ForeignKey(User)
    description = models.TextField()

    max_students = models.IntegerField()
    sessions = models.ManyToManyField(CourseSession) # e.g. Session 1 Introduction, Session 2 Basics, etc.
    rating = models.ManyToManyFields(StudentRating)
    date_added = models.DateTimeField()

class CourseEnrollment(models.Model):
    course = models.OneToOneField(CourseTemplate) # Each enrollment needs a new CourseTemplate Instance, so I can track it
    students = models.ManyToManyField(User)

Class CourseSession(models.Model):
    title = models.CharField(max_length=50)
    date = models.DateTimeField()
    details = models.CharField(max_length=100)
    address = models.TextField()
    #parent_course = models.ForeignKey(CourseTemplate)

class StudentRating(models.Model):
    student = models.ForeignKey(User)
    rating = models.IntegerField()
    #course = models.ForeignKey(CourseTemplate)

Now a teacher (=User) can create a CourseTemplate with all the required details first. After it's saved, he can create a concrete "enrollment" for e.g. this semester with 5 sessions. Maybe he changes after 8 enrollments some details (e.g. CourseTemplate.description or the course now only has 7 sessions instead of 8).

I'd like to have a 1:1 relationship between each CourseTemplate instance and each CourseEnrollment, so I can see for example: - Teacher X had 2012 three CourseEnrollments, two of them were the same or - which rating has he received for his second course.

The presented "Template" should always be the "newest", so I'd just need to get the latest instance by CourseTemplate.date_added.

Does anyone know how I can avoid this problem?

Thanks a lot!


You can duplicate any existing django model instance by clearing its primary key, and then saving it again.

ct = CourseTemplate.objects.all()[0]
# some original pk = None
# will be a new auto-incremented 

Need Your Help

iPhone - How to determine in which cell a button was pressed in a custom UITableViewCell

iphone uitableview uibutton

I currently have a UITableView that is populated with a custom UITableViewCell that is in a separate nib. In the cell, there are two buttons that are wired to actions in the custom cell class. Whe...

Sharing a result queue among several processes

python parallel-processing queue multiprocessing python-multiprocessing

The documentation for the multiprocessing module shows how to pass a queue to a process started with multiprocessing.Process. But how can I share a queue with asynchronous worker processes started ...