【问题标题】:How to use a function to pass the result to 'queryset'?如何使用函数将结果传递给'queryset'?
【发布时间】:2017-10-18 18:44:11
【问题描述】:

我正在开发一个 Python/Django 项目。我必须使用 YearArchiveView 基类,所以我有这个:

class ArchiveView(YearArchiveView):

    queryset = ArticlePage.objects.all()
    make_object_list = True
    date_field = 'date'
    template_name='btcmag/pages/archives_list.html'
    allow_future = False
    context_object_name = 'articles'

    def extract_month(self, article):
        'extracts the starting date from an entity'
        return article.date.month

    def extract_year(self, article):
        'extracts the starting date from an entity'
        return article.date.year

我想要一个返回正确查询集的函数,而不是 queryset = ArticlePage.objects.all()。比如:

queryset = getQuerySet()

同时我还要传入一些参数。

我尝试在类中定义函数,单独使用self 调用它,但我发现functionself 没有定义。

我必须在哪里定义函数/方法?

如何将其传递给queryset

【问题讨论】:

  • 你说的没有运气是什么意思?我们需要看看你是如何实现你的方法的。您是否考虑过使用额外方法的自定义管理器?
  • 刚刚编辑了问题。基本上我知道函数或自我没有定义。

标签: python django class django-queryset


【解决方案1】:

您可以在 Django 视图中覆盖/使用 get_queryset 方法,而不是设置 queryset

class ArchiveView(YearArchiveView):

    def get_queryset(self):
        ...magic here...

        return custom_queryset

【讨论】:

  • 其实很简单:应该在self in get_queryset 之内。所以在你找到的方法中:self.request.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-24
  • 2017-08-07
  • 2013-05-21
相关资源
最近更新 更多