Django 中的常见查询应该放在哪里?
我有一个相当复杂的查询集,目前我在单个视图中使用它来获取对象列表。
我想在其他几个视图中使用相同的查询集,但不希望只是多次复制代码。我可以使用管理器将查询集保留在一个位置,并在每个视图中使用它,除了查询依赖于每个页面上不同的日期。
据我了解,经理不允许您传递变量......所以我想知道应该将该查询放在哪里,以免在多个视图中不断重复。有什么想法吗?
FWIW,这是我的查询集,published_date 是每个页面上更改的变量:
day_publications = Publication.objects.filter(
Q(reading__end_date__gte=published_date) | Q(reading__end_date__isnull=True),
reading__start_date__lte=published_date,
).select_related('series',)
I have a queryset that is reasonably complicated, which I currently use in a single view for getting a list of objects.
I want to use the same queryset in a couple of other views but would prefer not to just copy the code multiple times. I could use a Manager, to keep the queryset in one place, and use that in each view except the query relies on a date which is different on each page.
As I understand it, Managers don't let you pass in variables... so I'm wondering where I should put this query so as not to keep repeating it in several views. Any thoughts?
FWIW, this is my queryset, and published_date is the variable that changes on each page:
day_publications = Publication.objects.filter(
Q(reading__end_date__gte=published_date) | Q(reading__end_date__isnull=True),
reading__start_date__lte=published_date,
).select_related('series',)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为你实际上应该使用经理。我习惯在我的管理器中使用这样的方法:
然后我在我的模型上运行查询:
当然,您可以跟进另一个过滤器调用并链接这些方法或做任何您想做的事情。这种方法没有任何问题,这就是管理者的目的:-)。
I think you should actually use a Manager. I habitually use methods like this in my managers:
Then I run the query on my model:
Of course, you can follow up with another call of filter and chain these or do whatever you want. There's nothing wrong with this kind of approach, that's what managers are here for :-).