How do we pick objects from a model to create copies in another model adding extra parameters in django?

Viewed 21

I have the following models:

class Questionnaire(models.Model):
    questionnaire_name = models.CharField(max_length=120, default="")
    ...

class Question(models.Model):
    question_body = models.TextField()
    ...

class QuestionnaireContent(models.Model):
    questionnaire = models.ForeignKey(Questionnaire)
    question = models.ForeignKey(Question)
    ...

The QuestionnaireContent model acts as a list of questionnaire templates. Those are assigned to users eventually, using:

class QuestionnaireAssignment(models.Model):
    user = models.ForeignKey(User)
    questionnaire = models.ForeignKey(Questionnaire)

Now, ideally, I would like this assignment to generate a new questionnaire 'instance' in another model which would have the following fields:

class QuestionnaireInstance(models.Model):
    user = models.ForeignKey(User)
    questionnaire = models.ForeignKey(Questionnaire)
    question = models.ForeignKey(Question)
    visibility = models.BooleanField()

But I would like that QuestionnaireInstance to be created automatically once a QuestionnaireAssignment instance is created. I guess I could rewrite the save function of QuestionnaireAssignmentbut I am wondering if there is a simpler/cleaner way to do this?

The idea is I want from the template questionnaires to create instance for users that can be customized for that user (adding attribute visibility and eventually changing the questions).

Thanks for your help!!

1 Answers

Overriding the save() method of QuetionnaireAssignment is one possibility. Note that you don't have to completely rewrite save() since you can call super().save().

Alternatively, use the postsave signal instead: docs.djangoproject.com/en/4.1/topics/signals

Related