【发布时间】:2017-09-28 13:46:29
【问题描述】:
我是 django/python 的新手,所以请多多包涵。
我想在 django 中创建某种“相关帖子”。我怎么能这样做?我正在关注这个: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})
任何帮助将不胜感激!
谢谢
----------- 更新 -----------
好的,乱码后,好像快成功了,但是报错了:
/trip/tour-island/处的ValueError
无法查询“bali island Tour”:必须是“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 %}
谢谢!
【问题讨论】:
标签: python django django-taggit