[英]Django filter objects based on related field
我有一個博客條目設置條目,其中有很多到類別字段。
categories = models.ManyToManyField(Category)
我有一個視圖,其中想列出所有條目,但是基於與類別有關聯的條目進行過濾,這些條目將在url中以段的形式表示。
到目前為止,這是我的視圖函數:
def category_detail(self, request, slug):
entries = Entry.live.all().filter()
categories = Category.objects.all()
return render(request, 'coltrane/entry_archive.html',
{"entries": entries, "categories": categories})
側邊欄中顯示一個類別列表,這就是為什么我在dict中傳遞這些值的原因。 我想在條目過濾器中添加一些邏輯以按類別返回某些內容。title= slug
您真的是指categories.title = slug
嗎?
entries = Entry.live.filter(categories__title=slug)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.