我有一些复杂的业务逻辑放在自定义 ModelManager 中。manager 方法返回值的元组而不是查询集。这被认为是不好的做法吗?如果是这样,推荐的方法是什么。我不想要视图中的逻辑,而 Django 没有服务层。另外,我的逻辑可能需要执行多个查询。
逻辑需要选择一个最接近当前时间的事件,再加上两边的 3 个事件。当放置在模板中时,了解最近的事件会很有帮助,因为这是最初显示在全屏滑块中的事件。
当前调用如下:
closest_event, previous_events, next_events = Event.objects.closest()
该逻辑目前确实可以正常工作。我即将转换我的应用程序。在模板中将事件数据呈现为 JSON,以便我可以在页面加载时引导主干.js 视图。我计划使用 TastyPie 将资源服务器端渲染到模板中。在我重构我的代码之前,最好知道我当前的方法不被认为是不好的做法。
这就是我的应用程序的方式。目前有效:
视图.py
class ClosestEventsListView(TemplateView):
template_name = 'events/event_list.html'
def get(self, request, *args, **kwargs):
context = self.get_context_data(**kwargs)
closest_event, previous_events, next_events = Event.objects.closest()
context['closest_event'] = closest_event
context['previous_events'] = previous_events
context['next_events'] = next_events
return self.render_to_response(context)
模型.py
from datetime import timedelta
from django.db import models
from django.utils import timezone
from model_utils.models import TimeStampedModel
class ClosestEventsManager(models.Manager):
def closest(self, **kwargs):
"""
We are looking for the closest event to now plus the 3 events either side.
First select by date range until we have a count of 7 or greater
Initial range is 1 day eithee side, then widening by another day, if required
Then compare delta for each event data and determine the closest
Return closest event plus events either side
"""
now = timezone.now()
range_in_days = 1
size = 0
while size < 7:
start_time = now + timedelta(days=-range_in_days)
end_time = now + timedelta(days=range_in_days)
events = self.filter(date__gte=start_time, date__lte=end_time, **kwargs).select_related()
size = events.count()
range_in_days += 1
previous_delta = None
closest_event = None
previous_events = None
next_events = None
position = 0
for event in events:
delta = (event.date - now).total_seconds()
delta = delta * -1 if delta < 0 else delta
if previous_delta and previous_delta <= delta:
# we have found the closest event. Now, based on
# position get events either size
next_events = events[:position-1]
previous_events = events[position:]
break
previous_delta = delta
closest_event = event
position += 1
return closest_event, previous_events, next_events
class Event(TimeStampedModel):
class Meta:
ordering = ['-date']
topic = models.ForeignKey(Topic)
event_type = models.ForeignKey(EventType)
title = models.CharField(max_length=100)
slug = models.SlugField()
date = models.DateTimeField(db_index=True)
end_time = models.TimeField()
location = models.ForeignKey(Location)
twitter_hashtag = models.CharField(null=True, blank=True, max_length=100)
web_link = models.URLField(null=True, blank=True)
objects = ClosestEventsManager()
def __unicode__(self):
return self.title