问题
I am using piston to write a JSON api for an application I am writing which handles recurring calendar events.
My API was working for regular events, when I attempted to add logic to handle the recurrence, I started getting the following error:
descriptor 'date' requires a 'datetime.datetime' object but received a 'unicode'
Here is my 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
is an IntegerField, actualDate
, startDate
, and endDate
are all DateField.
My URLconf accepts a uid, year, and month, all of which are passed as parameters to the CalendarHandler.read method.
回答1:
By using from datetime import datetime, timedelta
you have imported the datetime type from the datetime module. Thus when you call datetime.date
you are calling a method on the datetime type.
I think what you want is to use the date type from the datetime module:
- Change your import to
from datetime import datetime, timedelta, date
. - Call
date(year, month, 1)
instead ofdatetime.date(year, month, 1)
.
来源:https://stackoverflow.com/questions/10865143/descriptor-date-requires-a-datetime-datetime-object-but-received-a-unicode