使用Django,如何返回与标签关联的所有帖子

时间:2016-01-25 05:07:20

标签: python django

我正在尝试使用Django返回与标记关联的所有帖子。我搜索了一个解决方案,但找不到一个。我尝试编写代码,但它没有用。继承我的代码

models.py

class Tag(models.Model):
    title = models.CharField(max_length=250)
    slug = models.SlugField(max_length=200, unique=True)
    timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
    updated = models.DateTimeField(auto_now=True, auto_now_add=False)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse("posts:tag_index", kwargs={"slug": self.slug})

    class Meta:
        ordering = ["-timestamp"]


class Post(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
    slug = models.SlugField(unique=True)
    title = models.CharField(max_length=120)
    image = models.ImageField(upload_to=upload_location, null=True, blank=True,
                              width_field="width_field",
                              height_field="height_field")
    height_field = models.IntegerField(default=0)
    width_field = models.IntegerField(default=0)
    content = models.TextField()
    draft = models.BooleanField(default=False)
    publish = models.DateField(auto_now=False, auto_now_add=False)
    timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
    updated = models.DateTimeField(auto_now=True, auto_now_add=False)
    tags = models.ManyToManyField(Tag)

    objects = PostManager()

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse("posts:detail", kwargs={"slug": self.slug})

    class Meta:
        ordering = ["-timestamp"]

文章/ urls.py

from .views import post_list, post_create, post_detail, post_update, post_delete, sewp, tag_detail


urlpatterns = [
    url(r'^$',   post_list, name='list'),
    url(r'^tag/(?P<slug>[\w-]+)/$', tag_detail, name="tag_index"),
    url(r'^create/$', post_create, name='create'),
    url(r'^sewp$', sewp, name='sewp'),
    url(r'^(?P<slug>[\w-]+)/$', post_detail, name='detail'),
    url(r'^(?P<slug>[\w-]+)/edit/$', post_update, name='update'),
    url(r'^(?P<id>\d+)/delete/$', post_delete, name='delete'),
]

views.py

def tag_detail(request, slug=None):
query = slug
queryset_list = Post.objects.active()
tags_list = queryset_list.filter(tags__icontains=query).distinct()


instance = get_object_or_404(Tag, slug=slug)

context = {
    "instance": instance,
    "tags_list": tags_list
}
return render(request, "posts/tag_index.html", context)

tag_index.html

{% extends 'posts/base.html' %}

{% block content %}

{{ instance }}
{{ tags_list }}

{% endblock content %}

我只想返回所有标签并对其进行分页。

我可以修改以下代码来分页我的结果:

paginator = Paginator(queryset_list, 2)  # Show 25 contacts per page
page_request_var = "page"
page = request.GET.get(page_request_var)
try:
    queryset = paginator.page(page)
except PageNotAnInteger:
    # If page is not an integer, deliver first page.
    queryset = paginator.page(1)
except EmptyPage:
    # If page is out of range (e.g. 9999), deliver last page of results.
    queryset = paginator.page(paginator.num_pages)
context = {
        "queryset": queryset,
        "title": "Posts",
        "page_request_var": page_request_var,
        "today": today,
        "queryset_list": queryset_list,
        "paginator": paginator,
    }

任何有关此的指导或帮助将不胜感激

3 个答案:

答案 0 :(得分:0)

如果您想查找与标签相关的所有帖子,只需使用:

posts = Post.objects.filter(tag__title = query)

这将返回包含查询字符串指定标记的所有帖子。

详细了解如何在此处进行查询:https://docs.djangoproject.com/en/1.9/topics/db/queries/

答案 1 :(得分:0)

我会像这样使用通用的ListView:

from django.views.generic.list import ListView
from django.shortcuts import get_object_or_404

class TagView(ListView):
    template_name = 'posts/tag_index.html'

    def get_queryset(self):
        """ get the Tag object or return 404 """
        self.tag = get_object_or_404(Tag, slug=self.kwargs['slug'])
        return Post.objects.filter(tag=self.tag)

    def get_context_data(self, **kwargs):
        """ add a posts variable to context to use in template """
        context = super(TagView, self).get_context_data(**kwargs)
        context['posts'] = Post.objects.filter(tag=self.tag)

答案 2 :(得分:0)

这是基于views.py结构的语法

views.py:

def tag_index(request, slug=None):
   instance = get_object_or_404(Tag, slug=slug)
   ins = instance.post_set.all()
   context = {
       "instance": ins,
   }
   return render(request, "posts/tag_list.html", context)

然后在tags_list.html

{% for i in instance %}
  {{ i.title }}
  {{ i.content }}
{% endfor %}

希望这有助于某人