【问题标题】:How to grab related post/item using django-taggit?如何使用 django-taggit 抓取相关的帖子/项目?
【发布时间】: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


    【解决方案1】:

    similar_objects 正在返回一个trip 列表,你可以这样写:

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

    【讨论】:

    • 您好,感谢您的回复。错误消失了,但仍然没有显示任何内容。我期待类似循环的东西,但它是相关的帖子/项目。这是我的代码:pastebin.com/WG2ExtPH(我无法在此处格式化我的代码)。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2011-10-25
    • 2019-12-31
    • 2019-09-27
    • 1970-01-01
    • 1970-01-01
    • 2022-07-14
    • 2021-10-21
    • 1970-01-01
    相关资源
    最近更新 更多