I have setup like so (changed for simplicity)
class Author(models.Model)
name = models.CharField(max_length=100)
...
class Document(models.Model):
title = models.CharField(max_length=200)
content - models.TextField()
author = models.ForeignKey("Author", related_name="documents")
date_published = models.DateTimeField()
categories = models.ManyToManyField("Category")
class Category(models.Model):
name = models.CharField(max_length=100)
I'm pulling in the Author records but I only want to pull in related document records for each author that match specific criteria -- say, date_published and category.
I know the easy way to do this would be to pull in the records as a list of dictionaries using Author.objects.values()
, looping through each record and running:
author['documents']=Document.objects.filter(categories__in=[category_list], date_published__year=year)`
However, this is being generated for django-piston, and it seems to be happiest (particularly if you're defining your own fields!) if you return a QuerySet object.
Part of this may be because I made changes to the base django-piston code. Basically, the current version of the code here overwrites the fields
value. I changed this code so that I could change the fields
value for a Handler based on the request (so I could provide more details if the request was for a specific resource).
So I guess my question is three-fold:
- Is there a way to filter or somehow limit the subrecords of a record (i.e. filter
documents
for eachauthor.documents
) - If not, what is a functional way of doing this that also works with django-piston?
- Is there some easier, better way to do what I'm trying to do (display all the authors without their documents if an id is not given, but displaying the sub-records if filtering to just one author)?
Clarification
Okay, just to be clear, here is the pseudocode that I want:
def perhaps_impossible_view(request, categories=None, year=None):
authors = Author.objects.all()
authors.something_magical_happens_to_documents(category__in=[categories], date_published__year=year)
return render_to_response('blar.html', locals(), RequestContext(request))
So that if I were to put it in a template, this would work without any modifications:
{% for a in authors %}
{% for d in authors.documents.all %}
{{ d.title }} is almost certainly in one of these categories: {{ categories }} and was absolutely published in {{ year }}. If not, .something_magical_happens_to_documents didn't work.
{% endfor %}
{% endfor %}
something_magical_happens_to_documents
has to run and actually change the contents of documents
for each author record. It seems like this should be possible, but perhaps it isn't?