[英]How to grab related post/item using django-taggit?
I'm new in django/python, so please bear with me. 我是django / python的新手,所以请多多包涵。
I want to create some sort of "Related Post" in django. 我想在Django中创建某种“相关帖子”。 How I can do that? 我该怎么做? I'm following this : How to fetch related items when using taggit in django? 我正在关注: 在Django中使用taggit时如何获取相关项目?
but dont know how to use/implement it and how to render it in template. 但不知道如何使用/实现它以及如何在模板中呈现它。 This is my view : 这是我的看法:
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})
Any help would be greatly appreciated! 任何帮助将不胜感激!
Thank you 谢谢
----------- UPDATE ----------- -----------更新-----------
Okay, after babling with the code, it seems it's almost success, but it's error : 好吧,在浏览代码之后,似乎几乎成功了,但这是错误的:
ValueError at /trip/tour-island/ / trip / tour-island /的ValueError
Cannot query "bali island Tour": Must be "Tag" instance. 无法查询“巴厘岛旅游”:必须是“ Tag”实例。
Here is my updated code : 这是我更新的代码:
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})
In the template 在模板中
{% for trip in trip_related %}
<h1>{{ trip.title }}</h1>
{% endfor %}
Thank you 谢谢
----------- UPDATE [SOLVED!] ----------- -----------更新[已解决!] -----------
Using model_name.tags.similar_objects()
使用model_name.tags.similar_objects()
In views.py : 在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})
In template : 在模板中 :
{% for trip in trip_related %}
<h1>{{ trip.trip_judul }}</h1>
{% endfor %}
Thanks! 谢谢!
similar_objects
is returning a trip
list, you can write this sentence: 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.