' filter(category_slug=category) '是什么意思?



我有以下models.py设置,

class PostList(RoutablePageMixin, Page):
template = "Post_List.html"
intro = RichTextField(blank=True)
content_panels = Page.content_panels + [
FieldPanel("intro")
]
subpage_types = [
"PostDetail",
]
parent_page_type = [
"HomePage",
]
def get_context(self, request, *args, **kwargs):
context = super().get_context(request, *args, **kwargs)
context['posts'] = self.posts    
context['post_list'] = self
return context
def get_posts(self):
return PostList.objects.descendant_of(self).live()

@route(r'^tag/(?P<tag>[-w]+)/$')
def post_by_tag(self, request, tag, *args, **kwargs):
self.search_type = 'tag'
self.search_term = tag
self.posts = self.get_posts().filter(tag__slug=tag)
return Page.serve(self, request, *args, **kwargs)
@route(r'^category/(?P<category>[-w]+)/$')
def post_by_category(self, request, category, *args, **kwargs):
self.search_type = 'category'
self.search_term = category
self.posts = self.get_posts().filter(category__slug=category)
return Page.serve(self, request, *args, **kwargs)
@route(r'^$')
def post_list(self, request, *args, **kwargs):
self.posts = self.get_posts()
return Page.serve(self, request, *args, **kwargs)

问:我不明白在filter(category__slug=category)中category__slug是什么意思?根据Django官方文档中的字段查找,我从来没有见过这样的过滤器,只看到过xxx__gt或xxx__exact等。

我不明白在filter(category__slug=category)中category__slug是什么意思。

这意味着我们对post对象的categoryslug字段进行过滤。因此__slug而不是查找,它是Category模型的一个字段。因此,模型看起来像:

class Category(models.Model):
slug= models.SlugField()
# …
class Post(models.Model):
category= models.ForeignKey(Category, on_delete=models.CASCADE)
# …
因此,我们将生成如下的查询:
SELECT post.*
FROM post
INNER JOIN category ON post.category_id = category_id
WHERE category.slug =value-of-category-variable

相关内容

  • 没有找到相关文章

最新更新