for function in function

时间:2013-12-18 19:34:29

标签: python django

我的python知识仍然有限,我不知道如何在django中执行这个函数和类。 以后不用打印我会对原始数据库进行四次查询循环,有人可以帮我做这个正确的方法吗?

class WeeklyReports(models.Model):
    def FourWeeks(self, year, week):
        self.year = year
        self.week = week
        end = datetime(year, 1, 1) + relativedelta(weeks=week-1, weekday=SU)
        start = end - relativedelta(weeks=4, weekday=MO)
        mint, maxt = datetime.min.time(), datetime.max.time()
        for dt in rrule(WEEKLY, start, count=4):
            yield dt.combine(dt, mint), dt.combine(dt + timedelta(days=6), maxt)
            for start, end in FourWeeks(year, week):
                print start, end            

我希望收到类似countdown 4 weeks (week by week) back with python/django

的内容

但我明白了:

>>> from weeklyreport.models import WeeklyReports
>>> w = WeeklyReports()
>>> w.FourWeeks(2013, 22)
<generator object FourWeeks at 0x1eb5050>
>>> w.FourWeeks(2013, 22)
<generator object FourWeeks at 0x1eb50a0>
>>> w.FourWeeks(2013, 22)
<generator object FourWeeks at 0x1eb5050>
>>> w.FourWeeks(2013, 22)
<generator object FourWeeks at 0x1eb50a0>

此查询稍后将替换为print:

cursor = connections['nocdb'].cursor()
cursor.execute("SELECT DISTINCT (p.name) AS platform, count(e.id ) AS count FROM event e, lu_platform p WHERE e.platform_id = p.id AND e.sourcetype_id = 1 AND e.event_datetime BETWEEN %s AND %s AND e.sender_id  NOT IN ( 759, 73 ) GROUP BY p.name ORDER BY p.name", [start, end] )

1 个答案:

答案 0 :(得分:0)

你打算用Python写下缩进事项:

class WeeklyReports(models.Model):
    def FourWeeks(self, year, week):
        self.year = year
        self.week = week
        end = datetime(year, 1, 1) + relativedelta(weeks=week-1, weekday=SU)
        start = end - relativedelta(weeks=4, weekday=MO)
        mint, maxt = datetime.min.time(), datetime.max.time()
        for dt in rrule(WEEKLY, start, count=4):
            yield dt.combine(dt, mint), dt.combine(dt + timedelta(days=6), maxt)

然后您可以执行以下操作进行打印:

w = WeeklyReports()
for start, end in w.FourWeeks(year, week):
    print start, end

现在发生的事情是w.FourWeeks(2013, 22)创建了一个生成器(因为您正在使用yield语句)并且您只在使用生成器时“看到”结果。因此,在运行for start, end in FourWeeks(year, week):时,您只会在最后一部分中看到结果。