简体   繁体   English

字典中DateTime对象的Django序列化

[英]Django Serialization of DateTime Objects within Dictionary

My Django view method is below. 我的Django视图方法如下。 I want to pass place_data as a response from an HTTPRequest (within a getJSON call on the client side, but that's irrelevant to the issue). 我想将place_data作为HTTPRequest的响应传递(在客户端的getJSON调用内,但这与问题无关)。

I can pass the dictionary fine until I include the event_occurrences , which is doing some behind the scenes work to pass a dictionary of events with start and end times. 我可以很好地通过字典,直到包含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')

Here is the code attempting to do the serialization of the event_occurrences dictionary: 这是尝试对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

The call to event.upcoming_occurrences references the function below: 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

This is giving me the following error: 这给了我以下错误:

Exception Type: AttributeError
Exception Value:    'dict' object has no attribute '_meta'

I realize I cannot just call json.dumps() on my event_occurrences object, but can't figure out how to get around this serialization error (and this is my first time working with serialization in Python). 我意识到我不仅可以在我的event_occurrences对象上调用json.dumps(),而且无法弄清楚如何解决此序列化错误(这是我第一次使用Python进行序列化)。 Could someone please give me some direction as how and where the serialization needs to take place? 有人可以指导我进行序列化的方式和位置吗?

Thank you in advance! 先感谢您!

UPDATE: Added function calls to help with clarity of question. 更新:添加了函数调用以帮助解决问题。 Please see above. 请参阅上面。

Django's serialization framework is for QuerySets, not dicts. Django的序列化框架适用于QuerySet,而不适用于字典。 If you want to just dump a dictionary to JSON, just use json.dumps . 如果您只想将字典转储为JSON,请使用json.dumps It can easily be made to serialize objects by passing in a custom serialization class - there's one included with Django that deals with datetimes already: 可以通过传入自定义的序列化类来轻松地序列化对象-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