views:

33

answers:

2

I have a Django web application that's similar to the typical Q&A system.

A user asks a question. other users submit answers to that question:

  • Each user is allowed to submit up to N answers to each question, where N > 1 (so, say each user can submit no more than 3 answers to each question)
  • A user can edit his existing answers, or submit new answer(s) if he hasn't already reached his limit.

It's straightforward to do this if each user is allowed only 1 answer - just do:

unique_together = (("user.id", "question_id"),)

But in case of N>1, what is the best way to implement this?

+2  A: 

I'd add the following method to your Question model:

class Question(models.Model):

    def can_answer(self, user):
        return Answer.filter(question=self, user=user).count() < 3

You can use this method to decide if a user can add answers to the question.

Andrey Fedoseev
+2  A: 

This is a business rule that you will have to enforce at the application level rather than the database level. Hence you will have to check at the time of answering if the user can indeed post an answer. This can be done in multiple ways. Andrey's answer is one way of doing this. Another way would be to check for this during Answer.save(). If you prefer to keep the logic away from models you can define an utility function can_answer(user, question) that returns True or False and invoke it from the view.

Manoj Govindan