我有这样的设置(为简单起见进行了更改)
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)
我正在提取作者记录,但我只想为每个符合特定标准的作者提取相关文档记录——比如 date_published 和类别。
我知道做到这一点的简单方法是使用 将记录作为字典列表拉入Author.objects.values()
,遍历每条记录并运行:
author['documents']=Document.objects.filter(categories__in=[category_list], date_published__year=year)`
但是,这是为 django-piston 生成的,如果您返回 QuerySet 对象,它似乎是最快乐的(特别是如果您正在定义自己的字段!)。
部分原因可能是因为我对基础 django-piston 代码进行了更改。基本上,此处代码的当前版本会覆盖该fields
值。我更改了此代码,以便可以fields
根据请求更改 Handler 的值(因此,如果请求是针对特定资源的,我可以提供更多详细信息)。
所以我想我的问题是三个方面:
- 有没有办法过滤或以某种方式限制记录的子记录(即过滤
documents
每个author.documents
) - 如果不是,那么在 django-piston 上也可以使用的功能性方法是什么?
- 是否有一些更简单、更好的方法来做我想做的事情(如果没有给出 id,则显示所有作者没有他们的文档,但如果只过滤给一个作者,则显示子记录)?
澄清
好的,为了清楚起见,这是我想要的伪代码:
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))
因此,如果我将其放入模板中,则无需任何修改即可工作:
{% 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
必须运行并实际更改documents
每个作者记录的内容。看起来这应该是可能的,但也许不是?