Django - 一个视图,多个 URL?

发布于 2024-12-04 17:34:45 字数 1405 浏览 4 评论 0原文

我对 Python 和 Django 都很陌生,希望尽可能遵循最佳实践。我想整理以下代码以使其更易于使用。

我正在尝试设置一个可以通过多个 URL 访问的视图,这些 URL 提供将返回和显示查询集的不同参数。

我设置了以下 URL:

    url(r'^myrecords/$', login_required(RecordListView.as_view()), {'filter': 'all'}, name='myrecords'),
    url(r'^myrecords/page(?P<page>[0-9]+)/$', login_required(RecordListView.as_view()), {'filter': 'all'}, name='myrecords'),
    url(r'^myrecords/(?P<year>\d{4})/$', login_required(RecordListView.as_view()), {'filter': 'year'}, name='myrecords'),
    url(r'^myrecords/last(?P<months>[0-9]{1,2})months/$', login_required(RecordListView.as_view()), {'filter': 'month'}, name='myrecords'),

然后在我看来,我有这样的东西(实际上还有其他几个参数,但无论输入什么 URL,这些参数都应该保持不变。):

def get_queryset(self): 
    if (self.kwargs['filter'] == 'month'):
        x_months_ago = (datetime.date.today() - 
        datetime.timedelta(int(self.kwargs['months']) * 365 / 12))
        queryset = Record.objects.filter(user=self.request.user, 
        date__gte = x_months_ago.isoformat())
    elif (self.kwargs['filter'] == 'year'):
        queryset = Record.objects.filter(user=self.request.user, date__year=self.kwargs['year'])
    else
        queryset = Record.objects.filter(user=self.request.user)

这对我来说似乎很混乱。无论如何我可以让它更干净吗?是否可以将过滤器参数放入某种数据结构中,然后将它们传递到 Record.objects.filter 行,而不是多次写出整个内容?

任何建议将不胜感激。

谢谢。

I am fairly new to both Python and Django and would like to follow best practices where possible. I would like to tidy up the following code to make it easier to work with.

I am trying to set up a view which can be accessed through multiple URLs which provide different parameters for which a queryset will be returned and displayed.

I have set up the following URLs:

    url(r'^myrecords/

Then in my view I have something like this (There are actually several other parameters but these should remain the same regardless of the URL entered.):

def get_queryset(self): 
    if (self.kwargs['filter'] == 'month'):
        x_months_ago = (datetime.date.today() - 
        datetime.timedelta(int(self.kwargs['months']) * 365 / 12))
        queryset = Record.objects.filter(user=self.request.user, 
        date__gte = x_months_ago.isoformat())
    elif (self.kwargs['filter'] == 'year'):
        queryset = Record.objects.filter(user=self.request.user, date__year=self.kwargs['year'])
    else
        queryset = Record.objects.filter(user=self.request.user)

This seems very messy to me. Is there anyway I can make it cleaner? Is it possible to put the filter parameters in some sort of data structure and then just pass them to the Record.objects.filter line, rather than writing the whole thing out multiple times?

Any advice would be greatly appreciated.

Thanks.

, login_required(RecordListView.as_view()), {'filter': 'all'}, name='myrecords'), url(r'^myrecords/page(?P<page>[0-9]+)/

Then in my view I have something like this (There are actually several other parameters but these should remain the same regardless of the URL entered.):


This seems very messy to me. Is there anyway I can make it cleaner? Is it possible to put the filter parameters in some sort of data structure and then just pass them to the Record.objects.filter line, rather than writing the whole thing out multiple times?

Any advice would be greatly appreciated.

Thanks.

, login_required(RecordListView.as_view()), {'filter': 'all'}, name='myrecords'), url(r'^myrecords/(?P<year>\d{4})/

Then in my view I have something like this (There are actually several other parameters but these should remain the same regardless of the URL entered.):


This seems very messy to me. Is there anyway I can make it cleaner? Is it possible to put the filter parameters in some sort of data structure and then just pass them to the Record.objects.filter line, rather than writing the whole thing out multiple times?

Any advice would be greatly appreciated.

Thanks.

, login_required(RecordListView.as_view()), {'filter': 'year'}, name='myrecords'), url(r'^myrecords/last(?P<months>[0-9]{1,2})months/

Then in my view I have something like this (There are actually several other parameters but these should remain the same regardless of the URL entered.):


This seems very messy to me. Is there anyway I can make it cleaner? Is it possible to put the filter parameters in some sort of data structure and then just pass them to the Record.objects.filter line, rather than writing the whole thing out multiple times?

Any advice would be greatly appreciated.

Thanks.

, login_required(RecordListView.as_view()), {'filter': 'month'}, name='myrecords'),

Then in my view I have something like this (There are actually several other parameters but these should remain the same regardless of the URL entered.):

This seems very messy to me. Is there anyway I can make it cleaner? Is it possible to put the filter parameters in some sort of data structure and then just pass them to the Record.objects.filter line, rather than writing the whole thing out multiple times?

Any advice would be greatly appreciated.

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

羞稚 2024-12-11 17:34:45

当然。您可以使用字典:

my_queryset_filters = {
    'user': self.request.user,
    'date__year': self.kwargs['year'],
}

Record.objects.filter(**my_queryset_filters)

** 将字典扩展为关键字参数。 (还有 * 将列表扩展为位置参数。)

Sure. You can use a dictionary:

my_queryset_filters = {
    'user': self.request.user,
    'date__year': self.kwargs['year'],
}

Record.objects.filter(**my_queryset_filters)

The ** expands the dictionary into keyword arguments. (There's also * which expands a list into positional arguments.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文