[英]Django ORM - How to combine annotate and filter
我有以下型號:
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True, related_name='profile')
starred_authors = models.ManyToManyField(Author, related_name='users_with_stars')
class Author(models.Model):
name = models.CharField(max_length=250)
slug = models.SlugField(unique=True)
然后在作者模板中,我想展示當前登錄的用戶是否已經為該作者加星標,但是我在構建合適的查詢以使用ORM獲取此數據時遇到了麻煩。
在視圖中,我曾考慮使用如果作者尚未加星標,則為0的作者對象進行注釋,如果已加星標,則為1。 像這樣的東西:
def author_detail(request, slug):
user_id = request.user.pk
author = Author.objects.filter(slug=slug).filter(users_with_stars__user__pk=user_id).annotate(fav=Count('users_with_stars'))[0]
return render_to_response('app/author_detail.html',
{ 'author': author},
context_instance=RequestContext(request))
但上述情況並不好,因為如果當前用戶沒有為作者加星標,則找不到任何對象。 我想做的是以某種方式將最后一個過濾器放在注釋中,但我無法使其工作。
理想情況下,我希望在模板中執行以下操作:
{% if author.fav %}
<p>This is one of your favorite authors</p>
{% endif %}
任何建議表示贊賞。
我可能會將其拆分為模板字典中的單獨屬性,並通過直接檢查此用戶是否在由該作者加星標的用戶列表中來計算它。
就像是:
[...]
author = Author.objects.filter(slug=slug)
is_fav = author.users_with_stars.filter(pk=user_id).exists()
return render_to_response('app/author_detail.html',
{ 'author': author,
'is_fav': is_fav },
context_instance=RequestContext(request))
在模板中:
{% if is_fav %}
<p>This is one of your favorite authors</p>
{% endif %}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.