我正在Django创建一个博客,在那里我有一个基本模型PostType
,然后我将它扩展到网站上不同类型内容的几个子类。例如CodeSnippet
和BlogPost
。你知道吗
其思想是,这些内容类型基本相同,它们都有作者、标题、slug等,但它们也有一些独特的字段。例如,博客文章有一个文本内容字段,而代码段有一个编程语言相关字段。你知道吗
像这样:
class PostType(models.Model):
author = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE
)
title = models.CharField(
max_length=255,
unique=True,
)
class Meta:
abstract = True
class BlogPost(PostType):
content = models.TextField(
default='',
)
class GitHubRepo(PostType):
url = models.URLField(
unique=True
)
class CodeSnippet(PostType):
language = models.ForeignKey(
to=Language,
on_delete=models.CASCADE,
)
现在我想知道的是,是否有任何好的/首选的方法来查询数据库中基于父类PostType
的所有对象?你知道吗
对于网站的搜索,我目前正在查询每个不同的内容类型,然后合并结果。这是搜索视图的代码:
class Search(View):
def get(self, request):
context = {}
try:
query = request.GET.get('s')
blog_list = models.BlogPost.objects.filter(title__icontains=query)
projects_list = models.Project.objects.filter(title__icontains=query)
code_list = models.CodeSnippet.objects.filter(title__icontains=query)
from itertools import chain
context['result_list'] = list(chain(blog_list, projects_list, code_list))
except KeyError:
query = ''
context['title'] = 'Result for "{}"'.format(query)
return render(request, 'blog/search.html', context)
这一切都很好,但我想知道是否有任何方法可以同时查询PostType
的所有子级?你知道吗
Django知道存在什么样的儿童模型吗?我能用它吗?你知道吗
像PostType.child_objects.get()
或类似的东西。
即使是一种以编程方式获取所有子对象的方法,这样我就可以遍历它们并获取所有对象。你知道吗
就目前而言,我只有几个模型,但子模型的数量将增加,这将是伟大的,如果我可以保证,所有的模型将包括在网站搜索自动根据他们的关系,他们的父模型。你知道吗
PostType
是一个抽象的Model
(因此,它不创建物理表。只是为了在Django中使用继承(未来)。据我所知,您希望生成list
个QuerySet
,然后将其合并到一个list
中并在list/QuerySet
上迭代。你知道吗希望对你有帮助。你知道吗
如果
PostType
不是抽象模型,那么您应该能够直接查询它以获得所有这些子类结果否则,就不能用一个查询来实现这一点。你知道吗
这是可能的-以编程方式获取子类
相关问题 更多 >
编程相关推荐