I'm making an app that has multiple exams and multiple questions for each exam.
This is my current 'Question' model:
class Question(models.Model):
exam = models.ForeignKey(Exam, related_name='questions', on_delete=models.CASCADE)
question = models.TextField()
explanation = models.TextField(blank=True, null=True)
TOPICS = [
('NA', 'Not Available'),
('Algebra', 'Algebra'),
('Geometry', 'Geometry'),
('Trig', 'Trigonometry'),
('Calc', 'Calculus'),
('Chem', 'Chemistry'),
('Geology', 'Geology'),
('Physics', 'Physics'),
('Reading', 'Reading'),
('Writing', 'Writing'),
('Spelling', 'Spelling'),
('Comprehension', 'Reading Comprehension'),
]
topic = models.CharField(max_length=20, choices=TOPICS, default='NA')
order = models.IntegerField(default=0)
created = models.DateTimeField(auto_now_add=True)
attempts = models.IntegerField(default=0, editable=False)
correct_attempts = models.IntegerField(default=0, editable=False)
class Meta:
unique_together = ['exam', 'order']
def __str__(self):
return f'{self.exam} - Q{self.order}'
You can pretty much ignore all the fields except the 'order' field. This field shows what order the question will appear on the exam.
I would like for the default value of this order field to be the number of existing questions in the exam + 1.
For example, if my exam has two questions in it already, and I'm trying to add a third question, the order of this question will default to '3' unless I manually change it.
I know this doesn't work, but this solution would work similarly to this line of code:
default=Question.objects.filter(exam=self.exam).count() + 1
I'm inexperienced in creating functions for models in django so please let me know how I would do something like this, thanks!