簡體   English   中英

字典中DateTime對象的Django序列化

[英]Django Serialization of DateTime Objects within Dictionary

我的Django視圖方法如下。 我想將place_data作為HTTPRequest的響應傳遞(在客戶端的getJSON調用內,但這與問題無關)。

我可以很好地通過字典,直到包含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進行序列化)。 有人可以指導我進行序列化的方式和位置嗎?

先感謝您!

更新:添加了函數調用以幫助解決問題。 請參閱上面。

Django的序列化框架適用於QuerySet,而不適用於字典。 如果您只想將字典轉儲為JSON,請使用json.dumps 可以通過傳入自定義的序列化類來輕松地序列化對象-Django附帶了一個已經處理日期時間的類:

from django.core.serializers.json import DjangoJSONEncoder
json.dumps(mydict, cls=DjangoJSONEncoder)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM