我有一个模型管理器,它过滤一个查询集并返回今天开始的Records对象,即:time_start.day == datetime.now().day
。我不能在模型管理器上使用.count()或过滤器:
我收到了错误
>>>> Records.objects.today().count()
TypeError: count() takes exactly one argument (0 given)
>>>> Records.objects.today().filter(owner=self.request.user)
AttributeError 'list' object has no attribute 'filter'
我应该归还什么?不知道我怎么能让这个工作。这是经理:
class RecordManager(models.Manager):
use_for_related_fields = True
def today(self, **kwargs):
today = datetime.now(pytz.utc)
yesterday = today - timedelta(days=1)
initial_queryset = self.filter(time_start__gte=yesterday, **kwargs)
return_list = []
for record in initial_queryset:
if (record.time_start).day == today.day:
return_list.append(record)
return return_list
这是模型:
class Records(models.Model):
owner = models.ForeignKey(User, null=True)
activity = models.ForeignKey(Activity, null=True)
time_start = models.DateTimeField(null=True)
time_end = models.DateTimeField(null=True)
objects = RecordManager()
def is_running(self):
if self.time_end is None:
return True
else:
return False
def total_time(self):
return ((self.time_end-self.time_start).seconds)/60
def string_time_start(self):
if self.time_start:
return self.time_start.strftime("%H:%M %P")
else:
return None
def string_time_end(self):
if self.time_end:
return self.time_end.strftime("%H:%M %P")
else:
return None
def __unicode__(self):
return "%s - %s" % (self.activity.title, self.string_time_start())
非常感谢你的帮助。
答案 0 :(得分:2)
您从管理器方法返回一个列表而不是一个查询集,所以自然没有像count和filter这样的查询集方法都能正常工作。
修改强>
我不太确定你为什么要这样做。好像你只想在今天上午12点到11点59分之间查询记录,这是一个简单的查询:
today = datetime.date.today()
start = datetime.datetime.combine(today, datetime.time(0))
end = datetime.datetime.combine(today, datetime.time(23, 59))
return self.filter(time_start__gte=start, time_start__lte=end)
答案 1 :(得分:0)
正如@Daniel Roseman所写,当我需要返回一个查询集时,我正在返回一个列表。以防有人阅读问题并希望查看实际工作的代码:
class RecordManager(models.Manager):
use_for_related_fields = True
def today(self, **kwargs):
today = datetime.datetime.now(pytz.utc)
reference_date = datetime.datetime(today.year, today.month, today.day, tzinfo=pytz.utc)
return self.filter(time_start__gte=reference_date, **kwargs)
答案 2 :(得分:-1)
正确的解决方案是
Records.objects.count()