I'm new to Django, so excuse my ignorance :)
Say I have a model that has a couple of foreign key relations, and when I create an instance of the model I want it to automatically generate new instances for the foreign key objects as well. In this case I'm modelling course enrollment as a Group, and I am referencing the specific group as a foreign key on the model.
class Course(models.Model):
student_group = models.OneToOneField(Group, related_name="course_taken")
teacher_group = models.OneToOneField(Group, related_name="course_taught")
def clean(self):
if self.id:
try:
self.student_group
except Group.DoesNotExist:
self.student_group, _ = Group.objects.get_or_create(name='_course_' + self.id + '_student')
try:
self.teacher_group
except Group.DoesNotExist:
self.teacher_group, _ = Group.objects.get_or_create(name='_course_' + self.id + '_teacher')
It seems like I can hook into the clean method of the model to do this, but I'd like to be able to wrap the whole thing up in a single transaction, so that if it fails to create the Course later on, it won't create the related Group objects. Is there any way to achieve this?
Also, am I doing the wrong thing entirely here? Does Django provide a better way to do this?