字典中DateTime对象的Django序列化

2024-06-01 03:34:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我的Django视图方法如下。我想将place_数据作为HTTPRequest的响应传递(在客户端的getJSON调用中,但这与问题无关)。

我可以很好地传递字典,直到包含事件事件,这是做一些幕后工作来传递带有开始和结束时间的事件字典。

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')

下面是尝试对事件发生字典进行序列化的代码:

 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

调用事件。即将发生的事件引用以下函数:

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_occurrencess对象调用json.dumps(),但是我不知道如何避免这个序列化错误(这是我第一次在Python中使用序列化)。有人能告诉我序列化的方式和地点吗?

提前谢谢你!

更新:添加了函数调用以帮助澄清问题。请参见上文。


Tags: selfeventjsondatetimereturnbytesdefcallback
1条回答
网友
1楼 · 发布于 2024-06-01 03:34:12

Django的序列化框架是针对queryset的,而不是dict。如果只想将字典转储到JSON,只需使用json.dumps。通过传入自定义序列化类,可以很容易地对对象进行序列化—Django中已经包含了一个处理日期时间的类:

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

相关问题 更多 >