我有以下型号:
class Thread(models.Model):
name = models.CharField(max_length=50)
category = models.ForeignKey(Category)
class Post(models.Model):
thread = models.ForeignKey(Thread)
datetime = models.DateTimeField(auto_now_add=True)
author = models.ForeignKey(User)
这适用于我的论坛系统。
我需要获取类别X的所有Thread
,我需要有一些自定义属性,例如帖子最后一篇文章的datetime
和pk
,例如:
threads = Thread.objects.filter(category=x)
last_post = Post.objects.filter(thread=threads[0]).order_by('-pk')[0]
然后我想将所有内容传输到模板,以便我得到:
{{ t.pk }} as thread_pk
{{ t.last_post_pk }} as last_post_pk
等等。
答案 0 :(得分:1)
要获取每个线程的最后一篇文章,您应该使用聚合:
Post.objects.filter(thread__in=threads).values('thread').annotate(last_id=Max('id')).order_by()
这会从last_id
中的每个帖子中获取threads
。
答案 1 :(得分:0)
由于Django没有像你期望的那样加入SQL连接(请参阅我的评论以获得进一步的解释),我会在视图中解决它(或者可能是添加到Thread
类的方法)。请考虑以下示例视图:
def index(request):
res = []
for t in Thread.objects.filter(category__name='x'):
res.append((t, Post.objects.filter(thread=t).order_by('-datetime')[0]))
# Optionally sort by datetime here:
# res.sort(key=lambda x: x[1].datetime, reverse=True)
return render_to_response('index.html', {'result': res})
然后您可以在模板中使用它,如下所示:
{% for r in res %}
Thread {{ r.0.name }}, last post by {{ r.1.author.name }} on {{ r.1.datetime }}.
{% endfor %}
# This would give something like this:
# Thread mythread, last post by john on Oct. 21, 2011, 1:52 a.m..
通过创建Thread
和Post
s的元组,您并没有真正加入它们,但确实可以在模板中轻松使用它们。