Мой метод просмотра Django приведен ниже.Я хочу передать place_data как ответ от HTTPRequest (в рамках вызова getJSON на стороне клиента, но это не имеет отношения к проблеме).
Я могу нормально передать словарь, пока не включу event_occurferences , который выполняет некоторые закулисные действия для передачи словаря событий с временем начала и окончания.
def mobile_place_detail(request,place_id):
callback = request.GET.get('callback', 'callback')
place = get_object_or_404(Place, pk=place_id)
event_occurrences = place.events_this_week()
place_data = {
'Name': place.name,
'Street': place.street,
'City': place.city,
'State': place.state,
'Zip': place.zip,
'Telephone': place.telephone,
'Lat':place.lat,
'Long':place.long,
'Events': event_occurrences,
}
xml_bytes = json.dumps(place_data)
if callback:
xml_bytes = '%s(%s)' % (callback, xml_bytes)
print xml_bytes
return HttpResponse(xml_bytes, content_type='application/javascript; charset=utf-8')
Вот код, пытающийся выполнить сериализацию словаря event_occurferences:
def events_this_week(self):
return self.events_this_week_from_datetime( datetime.datetime.now() )
def events_this_week_from_datetime(self, now):
event_occurrences = []
for event in self.event_set.all():
event_occurrences.extend(event.upcoming_occurrences())
event_occurrences.sort(key=itemgetter('Start Time'))
counter = 0
while counter < len(event_occurrences) and event_occurrences[0]['Start Time'].weekday() < now.weekday():
top = event_occurrences.pop(0)
event_occurrences.insert(len(event_occurrences), top)
counter += 1
json_serializer = serializers.get_serializer("json")()
return json_serializer.serialize(event_occurrences, ensure_ascii=False)
return event_occurrences
Вызов event.upcoming_occurferences ссылается на функцию ниже:
def upcoming_occurrences(self):
event_occurrences = []
monday_time = datetime.datetime.combine(datetime.date.today() + relativedelta(weekday=MO), self.start_time)
all_times = list(rrule(DAILY, count=7, dtstart=monday_time))
weekday_names = ('monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday')
for idx, weekday in enumerate(weekday_names):
if getattr(self, weekday):
event_occurrences.append({
'Name': self.name,
'Start Time': all_times[idx],
'End Time': all_times[idx] + datetime.timedelta(minutes=self.duration)
})
return event_occurrences
Это дает мне следующую ошибку:
Exception Type: AttributeError
Exception Value: 'dict' object has no attribute '_meta'
Я понимаю, что не могу просто вызвать json.dumps () на моем event_occurrence объект, но не могу понять, как обойти эту ошибку сериализации (и я впервые работаю с сериализацией в Python).Может, кто-нибудь подскажет, как и где нужно проводить сериализацию?
Заранее спасибо!
ОБНОВЛЕНИЕ: добавлены вызовы функций, чтобы помочь с ясностью вопроса.Пожалуйста, см. Выше.