Django:基于父mod查询多个模型

2024-09-26 22:54:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在Django创建一个博客,在那里我有一个基本模型PostType,然后我将它扩展到网站上不同类型内容的几个子类。例如CodeSnippetBlogPost。你知道吗

其思想是,这些内容类型基本相同,它们都有作者、标题、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()或类似的东西。 即使是一种以编程方式获取所有子对象的方法,这样我就可以遍历它们并获取所有对象。你知道吗

就目前而言,我只有几个模型,但子模型的数量将增加,这将是伟大的,如果我可以保证,所有的模型将包括在网站搜索自动根据他们的关系,他们的父模型。你知道吗


Tags: 模型true类型内容objectstitle网站models
2条回答

PostType是一个抽象的Model(因此,它不创建物理表。只是为了在Django中使用继承(未来)。据我所知,您希望生成listQuerySet,然后将其合并到一个list中并在list/QuerySet上迭代。你知道吗

get_qs_list = [model.objects.filter(title__icontains=query) for model in PostType.__subclasses__()] # This contains QuerySet instances now.
for qs in get_qs_list:
    # qs iterator returns QuerySet instance
    for instance in qs:
        # instance iterator is single Model instance from QuerySet collection
        print(instance.title)

希望对你有帮助。你知道吗

如果PostType不是抽象模型,那么您应该能够直接查询它以获得所有这些子类结果

PostType.objects.filter(title__icontains=query)

否则,就不能用一个查询来实现这一点。你知道吗

Even a way to programmatically get all the children so that I could loop through them and get all the objects would be fine too.

这是可能的-以编程方式获取子类

PostType.__subclasses__()

相关问题 更多 >

    热门问题