2010-11-03 50 views
0

我想通過自己的日期時間來過濾數據庫條目:Django的數據庫查詢的日期時間

models.py:

from django.db import models 


class ContestEvent(models.Model): 
    year = models.DateTimeField() 
    month = models.DateTimeField() 

在我看來,我定義一個函數壓延:

def calendar(request, pYear, pMonth): 
    """ 
    Show calendar of events for specified month and year 
    """ 
    lYear = int(pYear) 
    lMonth = int(pMonth) 
    lCalendarFromMonth = datetime(lYear, lMonth, 1) 
    lCalendarToMonth = datetime(lYear, lMonth, monthrange(lYear, lMonth)[1]) 
    my_workouts = ContestEvent.objects.filter(id__year=lCalendarFromMonth, id__month=lCalendarToMonth) 
    lCalendar = html_calendar.WorkoutCalendar(my_workouts).formatmonth(lYear, lMonth) 

然後我得到以下錯誤:

Request Method: GET 
Request URL: http://127.0.0.1:8000/htmlcalendar/ 
Exception Type: TypeError 
Exception Value: 

int() argument must be a string or a number, not 'datetime.datetime' 

Exception Location: C:\Python25\lib\site-packages\django\db\models\fields\__init__.py in get_db_prep_lookup, line 225 

錯誤是相同的,當我用year = models.IntegerField()而不是year = models.DateTimeField()

這裏有什麼問題。我是一個Django初學者。 提前謝謝!

回答

0

我會說,如果你想要的月份和年份,然後使用IntegerField,當你這樣做,你不再需要創建日期時間對象傳遞給你的過濾器。試試這樣的:

class ContestEvent(models.Model): 
    year = models.IntegerField() 
    month = models.IntegerField() 

def calendar(request, pYear, pMonth): 
    """ 
    Show calendar of events for specified month and year 
    """ 
    lYear = int(pYear) 
    lMonth = int(pMonth) 
    my_workouts = ContestEvent.objects.filter(year=lYear, month=lMonth)