python - 字典中 DateTime 对象的 Django 序列化

标签 python django datetime serialization

我的 Django View 方法如下。我想将 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)

关于python - 字典中 DateTime 对象的 Django 序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4702044/

相关文章:

python - 将字符串转换为 HH :MM time in Python

php - Laravel 架构构建器 dateTimeTz 示例看起来如何?

python - 无法在 macOS 上使用 gdb 调试 tensorflow

python - 如何以与 pip 安装模块相同的方式导入自定义模块?

python - 如何将 pd.Series 添加到多索引 DataFrame 的子集?

Django 1.6 + AngularJS v1.2.6 + Amazon Aws

java - JSR 310::System.currentTimeMillis() 与 Instant.toEpochMilli()::TimeZone

Python - 解码 ('utf-8' )问题

python - 获取 'str' 到 Django forms.FileField()

python - django mssql 安装程序 : error initializing DB