私のDjangoビューメソッドは以下の通りです。私はplace_dataをHTTPRequestからの応答として渡したい(クライアント側のgetJSON呼び出し内で、問題に無関係)。辞書内の日付時刻オブジェクトのDjangoシリアル化
event_occurrencesを含めるまで、辞書の細かい部分を渡すことができます。これは、開始日と終了時刻のイベント辞書を渡すために使用されます。ここで
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_occurrences辞書のシリアル化を行うにしようとするコードです:
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_occurrences参照以下の関数の呼び出し:
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'
は、私はちょうど私のevent_occurrencesにオブジェクトjson.dumps()を呼び出すことはできません実現が、この直列化エラーを回避する方法を見つけ出すことはできません(これはPythonでシリアライズを扱う初めてです) 。誰かがシリアル化の仕方や方法を教えてください。
ありがとうございます!
UPDATE:質問の明確さに役立つ機能呼び出しが追加されました。上記をご覧ください。
混乱しています。その 'json_serializer'コードはどのように上記の関数に関係していますか?それはどこに呼ばれますか?なぜあなたはその辞書にも 'json.dumps'だけを使用できませんか?なぜあなたが尋ねた1つの質問に対して答えを受け入れなかったのですか? –