简体   繁体   中英

How to grab related post/item using django-taggit?

I'm new in django/python, so please bear with me.

I want to create some sort of "Related Post" in django. How I can do that? I'm following this : How to fetch related items when using taggit in django?

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/

Cannot query "bali island Tour": Must be "Tag" instance.

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()

In 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM