2017-05-01 55 views
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 %} 

谢谢!

回答

0

similar_objects返回一个列表trip,你可以写这样的句子:

trip_related = [a_trip 
       for a_trip in trip.tags.similar_objects() 
       if a_trip.misc_published 
       ][:3] 
+0

嗨, 感谢您的答复。错误消失了,但它仍然没有任何显示。我期望像循环一样,但它是相关的后/项目。 这里是我的代码:https://pastebin.com/WG2ExtPH(我不能在这里格式化我的代码)。 谢谢! –

+0

更新。其作品!谢谢@danihp! –

相关问题