2013-12-18 218 views
0

我的python知識仍然有限,我不知道如何在django中執行這個函數和類。 後來,而不是打印我會做四個查詢循環到原始數據庫,有人可以幫助我做到這一點正確的方式嗎?for循環功能

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> 

此查詢我將與打印後替換:

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]) 

回答

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):時纔會看到最後一部分的結果。

+0

但現在我無法啓動運行Django shell 報告$蟒蛇manage.py殼 /weeklyreport/models.py」 61行,在 爲起點,終點在FourWeeks(年,周): NameError:名字'FourWeeks'沒有被定義 – Robert

+0

@ user2859660對不起,現在已經修復了,我認爲打印語句應該放在你的視圖中,或者可以在shell窗口中執行。 –

+0

謝謝你的幫助,我發佈了這個問題,因爲我在那裏在我看來,我有工作定義 – Robert