[英]How to grab related post/item using django-taggit?
我是django / python的新手,所以请多多包涵。
我想在Django中创建某种“相关帖子”。 我该怎么做? 我正在关注: 在Django中使用taggit时如何获取相关项目?
但不知道如何使用/实现它以及如何在模板中呈现它。 这是我的看法:
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})
任何帮助将不胜感激!
谢谢
-----------更新-----------
好吧,在浏览代码之后,似乎几乎成功了,但这是错误的:
/ trip / tour-island /的ValueError
无法查询“巴厘岛旅游”:必须是“ Tag”实例。
这是我更新的代码:
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 %}
谢谢
-----------更新[已解决!] -----------
使用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 %}
谢谢!
similar_objects
正在返回trip
列表,您可以这样写:
trip_related = [a_trip
for a_trip in trip.tags.similar_objects()
if a_trip.misc_published
][:3]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.