【问题标题】:django db lookup for datetimedjango db 查找日期时间
【发布时间】:2010-11-03 13:05:20
【问题描述】:

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

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

【问题讨论】:

    标签: database datetime django-models filter


    【解决方案1】:

    我会说如果您想要月份和年份,然后使用 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)
    

    【讨论】:

      猜你喜欢
      • 2012-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-17
      • 2021-01-07
      • 2013-03-11
      • 2018-03-14
      • 1970-01-01
      相关资源
      最近更新 更多