bakarin
bakarin

Reputation: 652

how do i link a field to a multi valued field in django model

This model Profile has different information about user and also a field called quiz which is a ManytoMany field. This field shows the quizes the user has registered for. I want the total_score field to store score user obtained in each quiz he participated. How do i do it?

class Profile(models.Model):
  user=models.OneToOneField(User,related_name='Profile', on_delete=models.CASCADE)
  college=models.CharField(max_length=200)
  phone=models.IntegerField(blank=True,default=0)
  quiz=models.ManyToManyField(Quiz)
  total_score=models.IntegerField(default=0)

  def __str__(self):
    return self.user.username

class Quiz(models.Model):
  name=models.CharField(max_length=100)
  description=models.CharField(max_length=800,blank=True)
  dept=models.CharField(max_length=40)
  date=models.DateTimeField(default=datetime.datetime.now())
  duration=models.DurationField(default=datetime.timedelta(minutes=30))
  no_of_question=models.IntegerField(blank=True,default=0)
  theme=models.ImageField(blank=True)
  active=models.BooleanField(default=False)

  def __str__(self):
    return self.name

Upvotes: 3

Views: 274

Answers (1)

Sidhin S Thomas
Sidhin S Thomas

Reputation: 885

It seems you will need to create another model, maybe called result.

class Result(models.Model):
    profile = models.Foreignkey(Profile, on_delete=models.CASCADE)
    quiz = models.Foregnkey(Quiz, on_delete=models.CASCADE)
    score = models.IntegerField()

This relation should allow you to fulfil your requirements.

Upvotes: 3

Related Questions