描述符'date'需要'datetime.datetime'对象,但收到'unicode'

时间:2012-06-02 19:12:10

标签: python django django-piston

我正在使用活塞为我正在编写的处理重复日历事件的应用程序编写JSON api。

我的API适用于常规事件,当我尝试添加逻辑来处理重复时,我开始收到以下错误:

  

描述符'date'需要'datetime.datetime'对象,但收到'unicode'

这是我的handlers.py

from piston.handler import BaseHandler
from lessons.models import NewEvent, EachEvent
import calendar
from datetime import datetime, timedelta

class CalendarHandler(BaseHandler):
allowed_methods = ('GET',)
model = EachEvent
fields = ('actualDate', ('manager', ('firstName', 'lastName')))

def next_date(startDate, recurrence, rangeStart):
    sd = startDate
    while (sd < rangeStart):
        print sd;
        sd += datetime.timedelta(recurrence)
    return sd

def read(self, request, uid, month, year):
    qs = NewEvent.objects.filter(manager__boss = request.user).filter(endDate__gte=datetime.date(year, month, 1)).filter(startDate__lte=datetime.date(year, month, calendar.mdays[month]))
    lessonList = []
    qsList = list(qs)
    for l in qsList:
        if l.frequency == 0:
            x = EachLesson()
            x.lessonID = l.id
            x.actualDate = l.startDate
            x.manager = l.manager
            lessonList.append(x)
        else:
            sd = next_date(l.startDate, l.frequency, datetime.date(year, month, 1))
            while (sd <= datetime.date(year, month, calendar.mdays[month])):
                x = EachLesson()
                x.lessonID = l.id
                x.actualDate = sd
                x.manager = l.manager
                lessonList.append(x)
                sd += datetime.timedelta(recurrence)

    return lessonList

frequency是一个IntegerField,actualDatestartDateendDate都是DateField。

我的URLconf接受一个uid,year和month,所有这些都作为参数传递给CalendarHandler.read方法。

1 个答案:

答案 0 :(得分:7)

使用from datetime import datetime, timedelta您已从datetime模块导入日期时间类型。因此,当您调用datetime.date时,您正在调用日期时间类型的方法。

我认为你想要的是使用datetime模块中的日期类型:

  1. 将导入更改为from datetime import datetime, timedelta, date
  2. 致电date(year, month, 1)而非datetime.date(year, month, 1)