Use of an attribute in a set to many, given and encountered with the "Non-unique" field

I'm working on a new project with questions and some of the students are contributors . I want to have questions in the table, so for this I created Questions and match the Member's Questions by adding an attribute via ". But when I record a specific participant for a specific question, I can no longer use that participant for a new question! Why?

class Questions(models.Model):
    course = models.ForeignKey(Course, blank=False)
    question_author = models.ForeignKey(Author, blank=False)
    question_details = models.CharField(max_length=100, blank=False, default='')
    members = models.ManyToManyField(CourseParticipant, through='QuestionsParticipant')
    question_type = models.CharField(choices=question_types, max_length=1, default='1')
    timestamp = models.DateTimeField(auto_now_add=True)

class QuestionsParticipant(models.Model):
    question = models.ForeignKey(Questions)
    participant = models.ForeignKey(CourseParticipant, primary_key=True)
    tries = models.PositiveIntegerField(blank=False, default=0)
    flag = models.BooleanField(default=False)
    flag_reason = models.CharField(max_length=50, blank=True, default='')
    success = models.BooleanField(default=False)
    timestamp = models.DateTimeField(auto_now_add=True)


A screen depicts the error


source to share

2 answers

I think you have a logical problem in designing your relationship between the question and its participants. A many-to-many relationship in your context is that more than one participant can answer a question and a participant can answer multiple questions.

It means; you should never put primary_key=True

in any of your FKs in the table QuestionsParticipant

, otherwise you will break the M2M communication.

If you want the participant to answer only one question, you can place the table question = models.ForeignKey(Questions)

in CourseParticipant


Also, note that model names must always be unique. ( Question

, QuestionParticipant




Remove the argument primary_key=True

from the definition QuestionsParticipant.participant

. Primary keys are unique, so there can be no more than one record in the table for each member QuestionsParticipant




All Articles