django db查找datetime

时间:2010-11-03 13:05:20

标签: database datetime django-models filter

我正在尝试按日期时间过滤数据库条目:

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初学者。 提前谢谢!!

1 个答案:

答案 0 :(得分: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)