使用mongoDB的Django REST框架:基数为10的int()的无效文字

时间:2015-02-15 22:32:07

标签: django mongodb django-rest-framework

我正在使用django(1.5.11)和mongoDB(2.4.9)构建一个网站。由于我想添加REST API,我还安装了Django REST框架(3.0.5)。但我无法让序列化器与一个非常简单的模型一起正常工作(见下文),而是我得到了这个错误:

ValueError at /api/message/
invalid literal for int() with base 10

我认为这个错误与mongoDB标识符不是整数的事实有关。另请注意,我不想使用MongoEngine(和Django Rest Framework Mongoengine),因为我不想继续使用django哲学。

任何线索或提示?请在下面找到我的应用程序的最小示例。

models.py

from django.db import models
from djangotoolbox import fields

class Message(models.Model):
    created_on = models.DateTimeField(auto_now_add=True, null=True)
    text = models.TextField()
    tags = fields.ListField()

views.py

from django import http, template
from rest_framework import generics, renderers, parsers
from . import models, serializers

def messageList(request):
    if request.method == 'GET':
        messages = models.Message.objects.all()
        serializer = serializers.MessageSerializer(messages, many=True)
        return JSONResponse(serializer.data)

class JSONResponse(http.HttpResponse):
        def __init__(self, data, **kwargs):
                content = renderers.JSONRenderer().render(data)
                kwargs['content_type'] = 'application/json'
                super(JSONResponse, self).__init__(content, **kwargs)

serializers.py

from rest_framework import serializers
from . import models

class MessageSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Message
        fields=('id' , 'text',)

urls.py

from django.conf.urls import patterns, include, url
from . import views

urlpatterns = patterns('',
    url(r'^api/message/$', views.messageList),
)

1 个答案:

答案 0 :(得分:2)

您必须在序列化程序中将id字段添加为字段

<强> serializers.py

class MessageSerializer(serializers.ModelSerializer):
    id = serializers.CharField()
    class Meta:
        model = models.Message
        fields=('id' , 'text',)