I’m currently using django with tastypie. I need to implement an api for Questions and answers. I’ve created the following resources tied to the Question and Answer model respectively:
class QuestionResource(ModelResource):
answers = fields.ToManyField("material.resources.AnswerResource",
"answer_set",blank=True,full=True)
class AnswerResource(ModelResource):
question = fields.ToOneField(QuestionResource,'question')
In my mind answers belong to questions, and a user shouldn’t be able to create a question without the corresponding answers. In my previous iteration I used a django formset to contain the information both for the question and the related answers. With tastypie, there’s not a neat out-the-box solution (as far as I know) for this scenarion.
Should I only allow requests to the question resource which will then update the corresponding answers, or should I couple the 2 resource losely, meaning that the user then has to make sure to submit the associated answers after the question is created. The Former seems to me to be better in principle since the latter can produce question without answers which in principle should never be the case.
Well, I think it’s not possible to create two different resources at once in a RESTful API (because you can’t POST to two different URLs at once). So to keep the API clean and RESTful I’d rather suggest you follow the latter approach and allow for creating them separately (unless you combine them into one resource). This might not be as bad as it seems.
I understand this may yield questions without answers (I assume the question is the first entity which should appear and this question should then be answered). However in your application you could overcome this by not operating on questions unless answered (e.g. don’t display them anywhere).
You could even go one step further and define a custom manager class which filters those unanswered question out by default, like so:
then
Question.objects.all()would only return questions with answers andQuestion.all_questions.all()would include unanswered question as well.In order to keep your database relatively clean you could get rid of old, unanswered questions periodically (e.g. using Cron).
I hope this makes you lean towards separation a bit more 🙂