0
我是django/python中的新成員,請耐心等待。如何使用django-taggit抓取相關的帖子/項目?
我想在django中創建某種「Related Post」。我該怎麼做?我正在如下:How to fetch related items when using taggit in django?
但不知道如何使用/實現它,以及如何在模板中呈現它。這是我的看法:
def trip_list(request):
trip_list = Trip.objects.filter(misc_published=True).order_by('-misc_published')[:12]
related = Trip.objects.filter(tags=trip_list.tags.similar_objects())[:3]
return render(request, 'app_trip/trip_list.html', {'trip_list': trip_list})
任何幫助將不勝感激!
謝謝
----------- ----------- UPDATE
好吧,用代碼babling後,現在看來,這是幾乎成功,但它的錯誤:
ValueError異常在旅行/旅行/旅遊島/
無法查詢「巴厘島之旅」:必須是「標籤」的實例。
這是我更新的代碼:
def trip_single(request, slug):
trip = get_object_or_404(Trip, slug=slug)
trip_related = Trip.objects.filter(misc_published=True, tags=trip.tags.similar_objects())[:3]
return render(request, 'app_trip/trip_single.html', {'trip': trip}, {'trip_related': trip_related})
在模板
{% for trip in trip_related %}
<h1>{{ trip.title }}</h1>
{% endfor %}
謝謝
----------- UPDATE [解決!] -----------
使用model_name.tags.similar_objects()
在views.py:
def trip_single(request, slug):
trip = get_object_or_404(Trip, slug=slug)
trip_related = trip.tags.similar_objects() # Where the magic happen
return render(request, 'app_trip/trip_single.html', {'trip': trip, 'trip_related': trip_related})
在模板:
{% for trip in trip_related %}
<h1>{{ trip.trip_judul }}</h1>
{% endfor %}
謝謝!
嗨, 感謝您的答覆。錯誤消失了,但它仍然沒有任何顯示。我期望像循環一樣,但它是相關的後/項目。 這裏是我的代碼:https://pastebin.com/WG2ExtPH(我不能在這裏格式化我的代碼)。 謝謝! –
更新。其作品!謝謝@danihp! –