Alireza Ghaffari
Alireza Ghaffari

Reputation: 1104

Using through attribute in a many-to-many filed and encountering with "Non-Unique" field requirement

I am working on a new project including questions and some students as participants, I want to have questions participants in a table,so for doing it, I created a Questions table and made a correspond to QuestionsParticipant by adding "through" attribute. But when I record a specific participant for a specific question, I can't use that participant for a new question anymore! 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

Upvotes: 2

Views: 32

Answers (2)

Ozgur Vatansever
Ozgur Vatansever

Reputation: 52163

I think you have a logical problem in designing your relationship between a question and its participants. Many-to-many relationship in your context is that a question can be answered by more than one participant and a participant can answer more than one question.

That means; you should never put primary_key=True to any of your FK in QuestionsParticipant table otherwise you'd break M2M relationship itself.

If you want a participant to answer only one question, you can put question = models.ForeignKey(Questions) to CourseParticipant table.

Besides, please note that model names should always be singular. (Question, QuestionParticipant, etc.)

Upvotes: 1

catavaran
catavaran

Reputation: 45575

Remove the primary_key=True argument from the QuestionsParticipant.participant definition. Primary keys are unique so for each participant there can be no more that one record in the QuestionsParticipant table.

Upvotes: 1

Related Questions