如何在搜索结果中请求 url 该模型的详细视图?

How to request url of that model detail views in search result?

我在三个模型中搜索,所有模型都有不同的详细视图,但我无法弄清楚如何告诉 Django 定位视图到他们的模型 这是我对模型搜索的看法

def search_item(请求): 结果 = [] search_item = request.GET.get("搜索")

if search_item:
    q = Q(title__icontains=search_item) | Q(written_by__icontains=search_item)
    for model in (crypto, News, Movie):
        results.extend(model.objects.filter(q))

return render(request, "result.html", {"results": results})

以及该模板

{% for result in results %}
  <a class="blog-card" href="">
    <div class="card col-4" style="width: 18rem;">
      <img src="{{ result.title_image.url }}" class="card-img-top" width="100%" height="200px">
      <div class="card-body">
        <h5 class="card-title text-center" style="color:black">{{ result.title|truncatewords:7 }}</h5>
        <p class="card-text text-center" style="color:black">{{ result.info|truncatewords:10 }}</p>
        <p class="number text-center" style="color: black;"> Wriiten By:<strong> {{ result.written_by }}</strong></p>
        <p class="last text-center" style="color: black;"> Last update:<strong> {{ result.joined_date }}</strong></p>
      </div>
    </div>
  </a>
{% endfor %}

并且所有模型都有不同的细节视图,那么如何做到这一点 urls.py

  path('crypto/<slug:title>/',views.ttt_read,name="ttt_read"),
    path('news/<slug:title>/',views.news_read,name="news_read"),
    path('movie/<slug:title>/',views.movie_read,name="movie_read"),
    path('penmen/search/',views.search_item,name='search')

我们将不胜感激任何帮助和建议

为每个模型定义一个 get_absolute_url() 方法。

示例:

    from django.urls import reverse

    class News(models.Model):
        ...
        def get_absolute_url(self):
            return reverse('news_read', args=[slug(self.title)])

Then in your template you can just do:

    ...
    <a class="blog-card" href="{{result.get_absolute_url}}">
    ...