How To Apply Condition In Boolean Field In Django Rest Framework?

I am working on a blog type website.

where students will ask question and teacher will answer it.

I put two user role Teacher and student

class User(AbstractBaseUser, PermissionsMixin):
    USER_TYPE = (
        ('None', 'None'),
        ('Student', 'Student'),
        ('Teacher', 'Teacher'),
    user_type = models.CharField(choices=USER_TYPE, default='Student', max_length=50)

This is the user model where the role is defined.

Post model for submitting the question and Comment model for answering it.

In the Post model I put on field is_answered and as default put it False

class add_question(models.Model):
    created_by = models.ForeignKey(User, blank=False, on_delete=models.CASCADE)
    is_answered = models.BooleanField(default=False)

And the answer model [which is comment one] is referred to as the foreign key of the question

class submit_answer(models.Model):
    question_id = models.ForeignKey(
        add_question, blank=False, on_delete=models.CASCADE)
    created_by = models.ForeignKey(User, blank=False, on_delete=models.CASCADE)

Both question and answer model contains created_by field and ForeignKey of User and answer model contains another ForeignKey of question.

so I need when the teacher role will put a comment the is_answered Field in add_question model should turn as true. as student also can comment on his/er question so I need on condition to apply.

I am using serializer as I need API of this

So, should I modify on my or and how should I do that!

It would be great help if someone guide me how to do it?

Thanks and let me know if any other information needed.



The best practice would be adding such codition in save() method of models.Model. You should name your Model classes differently, like Question and Answer, because after creating, if you want to edit or something, it would be weird if you have to search for submit_answer, right? And as @wjh18 said, use CamelCase in classes.

Also question_id is usually bad idea, better think of question, because it will lead directly to the whole object, not its id.

class Answer(models.Model):
    question = models.ForeignKey(Question, blank=False, on_delete=models.CASCADE)
    created_by = models.ForeignKey(User, blank=False, on_delete=models.CASCADE)

    def save(self, *args, **kwargs):
        if self.created_by.user_type == 'Teacher' and not self.question.is_answered:
            self.question.is_answered = True
        super().save(*args, **kwargs)