簡體   English   中英

如何使用django-taggit抓取相關帖子/項目?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM