Context
I have been having conflict. Currenly, I am creating a question answer application. Each question has a tag, and I want to show the most popular tags (e.g. tags that have the most questions associated with it).
Specifics
I am using django-taggit
's TaggableManager
to do so. Here is the model definition of the Question
:
class Question(models.Model):
tags = TaggableManager()
date = models.DateTimeField(default=timezone.now)
text = models.TextField(null=True)
So now I have the several tags attached to questions.
Question
How do I make a tastypie resource to display the tags and sort them by which tag has the most questions associated with it?
My attempts
I have really only had one decently successful attempt at making this work. Here is the tastypie resource:
class TagResource_min(ModelResource):
def dehydrate(self, bundle):
bundle.data['total_questions'] len(Question.objects.filter(tags__slug=bundle.obj.slug))
return bundle
class Meta:
queryset=Tag.objects.all()
Returns a nice JSON with a variable called total_questions
with the number of questions associated with it. Although, dehydrate is after the sort_by
part of the request cycle specified here, so I cannot sort the resource by total_questions
. Here is the JSON:
{
"meta": {
"limit": 20,
"next": null,
"offset": 0,
"previous": null,
"total_count": 13
},
"objects": [
{
"id": 1,
"name": "testing tag",
"resource_uri": "/full/tag/1/",
"slug": "testing-tag",
"total_questions": 2
},
...]
}
Another attempt I had went a different way trying to make the queryset
be formed from the Question
model:
queryset=Question.objects.filter(~Q(tags__slug=None)).values('tags', 'tags__slug').annotate(total_questions=Count(Tag))
The problem with this was that the filter
function turns the result to dict
type instead of models.Model
type. The key difference was that models.Model
has the attribute pk
which is a type of identification, and the dict
does not have that.
Any contribution is much appriciated! Thank you!