开发者

Django model with 3 many to many fields

开发者 https://www.devze.com 2023-03-18 15:51 出处:网络
I have these models class User(models.Model): user_name = models.CharField() ph_number = models.CharField()

I have these models

class User(models.Model):
    user_name = models.CharField()
    ph_number = models.CharField()

class ExamPaper(models.Model):
    paper_name = models.CharField()
    paper_subject = models.CharField()

class Questions(models.Model):
    paper = models.ManyToManyField(ExamPaper, related_name='question_set')
    question_num = models.IntegerField()
    question_text = models.TextField()

Now I want to store the results of each question by each user for each paper. Paper will have multiple questions and a question may also belong to multiple papers. User may give multiple papers and multiple questions.

I want mysql table to have user, paper and question to define primary key taken all together and two more fields 'marks' and 'result'. I'm not able to understand how to do this in django models. Will this work:

class Result(models.Model):
     user = models.ManyToManyFie开发者_JAVA技巧ld(User)
     paper = models.ManyToManyField(ExamPaper)
     question = models.ManyToManyField(Question)
     marks = models.IntegerField()
     result = models.CharField()

Please anyone can anyone explain?


You should use one-to-many (ForeignKey) relationships instead of many-to-many:

class Result(models.Model):
     user = models.ForeignKey(User)
     paper = models.ForeignKey(ExamPaper)
     question = models.ForeignKey(Question)
     marks = models.IntegerField()
     result = models.CharField()

     class Meta:
         unique_together = (("user", "paper", "question"), )

If a question can appear only on one exam paper, then Question.paper should also be a ForeignKey and you could remove the paper field from Result.


To begin with, you probably want the unique_together option for the _meta class. See: https://docs.djangoproject.com/en/1.3/ref/models/options/#unique-together

EDIT: Looks like django requires at least one primary key field. https://docs.djangoproject.com/en/1.3/topics/db/models/#automatic-primary-key-fields

0

精彩评论

暂无评论...
验证码 换一张
取 消