在我的Django项目中,我需要计算行程的日期范围,以查看此行程目前是否正在进行中。
class TourTemplate(models.Model):
length = models.IntegerField()
description = models.TextField(max_length=1000)
...
class Trip(models.Model):
tourtemplate = models.ForeignKey(TourTemplate)
start = models.DateField()
...
我将此添加到我的Trip模型中:
def end(self):
length = self.tourtemplate.length
start = self.start
a = start + timedelta(days=length)
return a
在shell中它可以工作并返回单个对象的结束日期。但是,我如何过滤我的查询集,以便只在start和计算的结束日期之间获得对象?
答案 0 :(得分:1)
<?php
/**
*
*/
function myexample_block_info() {
$blocks['myblock'] = array(
'info' => t('My Custom Modue'),
);
return $blocks;
}
function myexample_block_view($delta = '') {
$block = array();
$results = db_select('users','a')
->fields('a', array('name', 'mail'))
->execute();
$header = array(t('NAME'), t('MAIL'));
$rows = array();
foreach ($results as $node) {
$rows[] = array(
$node->name,
$node->mail,
);
}
$block['content'] = theme('table', array('header' => $header, 'rows' => $rows));
return $block;
}
现在,您可以致电:
# First, define a manager subclass
class TripManager(models.Manager):
def get_queryset(self):
length= self.tourtemplate.length
start= self.start
end=start+ timedelta(days=length)
return super(TripManager, self).get_queryset().filter(date__range=[start, end])
class Trip(models.Model):
objects = models.Manager() # The default manager.
current_trip = TripManager() # New manager
两个消失:
尝试以上解决方案。希望它有所帮助:)
答案 1 :(得分:0)
无法弄清楚如何将我的计算值插入到查询集中。我的解决方案是为结束日期添加另一个日期字段(editable = False),并在创建新旅程时计算并保存结束日期:
# Calculate end date on save
def save(self, *args, **kwargs):
self.end = self.start+ timedelta(days=self.tourtemplate.length)
super(Trip, self).save(*args, **kwargs)