使用referencefield的listfield时,Document Serializer返回object而不是id

时间:2017-01-10 11:31:37

标签: python django mongodb mongoengine

我正在使用django 1.5.11 for mongodb。 Serializer.data为listfield中给出的所有引用返回对象而不是id。 我以json格式发布数据,如下所示:

{
    "author_id": ["5874a85b58c1d23a5343cc87","5874a85058c1d23a5343cc86"],
    "title":"my book1"
}

print serializer.data给出:

{'author_id': [<Authors: Authors object>, <Authors: Authors object>], 'Cost': None, 'id': u'5874c75a58c1d23ec8adf40f', 'title': u'my book1'}

我期待serializer.data为:

{'id': u'5874c75a58c1d23ec8adf40f', u'author_id': [u'5874a85b58c1d23a5343cc87', u'5874a85058c1d23a5343cc86'], u'title': u'my book1'}

我的文件如下:

model.py:

from django.db import models
from rest_framework_mongoengine.serializers import DocumentSerializer
from mongoengine.document import Document
from mongoengine.fields import EmbeddedDocumentField,ListField,ReferenceField, StringField, ObjectIdField, IntField, BooleanField, FloatField, DateTimeField
from mongoengine import connect, CASCADE
from pymongo import ReadPreference


connect('mydb16', username='admin', password='admin123')

class Authors(Document):    
    author_name = StringField(max_length=30)
    author_country = StringField(max_length=30)

class Books(Document):
    author_id =ListField(ReferenceField('Authors',required = True))
    #author_id =ReferenceField('Authors')
    title = StringField(max_length=30)
    Cost = IntField()

serializer.py:

from app.models import Authors
from app.models import Books

from rest_framework_mongoengine.serializers import DocumentSerializer
from rest_framework import serializers

class AuthorsSerializer(DocumentSerializer):

    class Meta:
        model = Authors
    def to_internal_value(self, data):
        return super(DocumentSerializer, self).to_internal_value(data)



class BooksSerializer(DocumentSerializer):
    class Meta:
        model = Books

    def to_internal_value(self, data):
        return super(DocumentSerializer, self).to_internal_value(data)      

views.py

from app.serializers import AuthorsSerializer
from app.serializers import BooksSerializer
from rest_framework import status
from app.models import Authors
from app.models import Books
from rest_framework.views import APIView
from rest_framework.response import Response

class AuthorsList(APIView):
    def get(self,request,fromat=None):
        print "I am Authorlist get..."    
        author = Authors.objects.all()               
        serializer = AuthorsSerializer(author, many=True)
        print "\n\nserializers data: " , serializer.data, "\n\n"
        return Response(serializer.data)

    def post(self, request, format=None):
        print "I am Authorlist post"    
        data = request.data
        print "\nData: ", data , "\n\n"        
        serializer = AuthorsSerializer(data=data)


        if serializer.is_valid():   
            serializer.save()

            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

class BooksList(APIView):

    def get(self,request,format=None):
        print "I am Bookslist get"    
        books = Books.objects.all()      
        print "books :",books         
        serializer = BooksSerializer(books, many=True)
        print "serializer :",serializer
        print "serializer.data :",serializer.data
        return Response(serializer.data)        

    def post(self, request, format=None):
        print "I am Bookslist post"    
        data=request.data
        print "data :" , data
        print "\nData: ", data , "\n\n"

        serializer = BooksSerializer(data=data)

        if serializer.is_valid():
            serializer.save()
            print "serializer.data ", serializer.data
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) 

urls.py:

from django.conf.urls import patterns, url
import views
from django.contrib import admin



urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^authors/$', views.AuthorsList.as_view()),
   # url(r'^books/(?P<pk>[0-9a-f]+)/$', views.BooksList.as_view()), 
    url(r'^books/$', views.BooksList.as_view()),   

]

settings.py:

# Django settings for new_project project.

DEBUG = True
TEMPLATE_DEBUG = DEBUG

ADMINS = (
    # ('Your Name', 'your_email@example.com'),
)

MANAGERS = ADMINS

DATABASES = {
    'default': {
        'ENGINE': 'django_mongodb_engine', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'mydb16',                      # Or path to database file if using sqlite3.
        # The following settings are not used with sqlite3:
        'USER': 'admin',
        'PASSWORD': 'admin123',
        'HOST': '127.0.0.1',                      # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
        'PORT': '27017',                      # Set to empty string for default.
    }
}

# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
ALLOWED_HOSTS = []

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'America/Chicago'

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'

SITE_ID = u'5874a7aa58c1d23a3040bb5f'

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True

# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True

# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True

# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/var/www/example.com/media/"
MEDIA_ROOT = ''

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://example.com/media/", "http://media.example.com/"
MEDIA_URL = ''

# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/var/www/example.com/static/"
STATIC_ROOT = ''

# URL prefix for static files.
# Example: "http://example.com/static/", "http://static.example.com/"
STATIC_URL = '/static/'

# Additional locations of static files
STATICFILES_DIRS = (
    # Put strings here, like "/home/html/static" or "C:/www/django/static".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
)

# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#    'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

# Make this unique, and don't share it with anybody.
SECRET_KEY = '7x17q1(2v(r&6)66)cjwfql#h@ng#+do90fi-(yj74k)e=gli0'

# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
#     'django.template.loaders.eggs.Loader',
)

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    # Uncomment the next line for simple clickjacking protection:
    # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'new_project.urls'

# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'new_project.wsgi.application'

TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
)

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'app',
    'django.contrib.admin',
    # Uncomment the next line to enable the admin:
    # 'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',
)

SESSION_SERIALIZER = 'django.contrib.sessions.serializers.JSONSerializer'

# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}

我在虚拟环境中安装了django。我的冻结点如下:

Django==1.5.11
django-browserid==2.0.2
django-classy-tags==0.8.0
django-missing==0.1.18
django-mongo-auth==0.1.3
django-mongodb-engine==0.6.0
django-redis-sessions==0.5.6
django-rest-framework-mongoengine==3.3.0
django-sekizai==0.10.0
django-websocket-redis==0.4.7
djangorestframework==3.1.2
djangorestframework-jwt==1.9.0
djangotoolbox==1.8.0
gevent==1.1.2
greenlet==0.4.10
mongoengine==0.9.0
oauthlib==2.0.1
pika==0.10.0
Pygments==2.1.3
PyJWT==1.4.2
pymongo==2.8
python-dateutil==2.6.0
python-openid==2.2.5
pytz==2016.10
redis==2.10.5
requests==2.12.3
requests-oauthlib==0.7.0
rest-condition==1.0.3
six==1.10.0
tweepy==3.5.0

我被困在这里,任何帮助都将不胜感激。 提前谢谢......

1 个答案:

答案 0 :(得分:0)

好的,最后得到解决....这是版本兼容性问题。

我再次使用以下版本安装了我的虚拟环境:

Django==1.5.11
django-browserid==2.0.2
django-classy-tags==0.8.0
django-crispy-forms==1.6.1
django-filter==1.0.1
django-missing==0.1.18
django-mongo-auth==0.1.3
django-mongodb-engine==0.6.0
django-rest-framework-mongoengine==3.3.1
django-sekizai==0.10.0
djangorestframework==3.1.2
djangorestframework-jwt==1.9.0
djangotoolbox==1.8.0
httplib2==0.10.3
mongoengine==0.9.0
oauthlib==2.0.1
paho-mqtt==1.2
pika==0.10.0
Pygments==2.1.3
PyJWT==1.4.2
pymongo==2.8.1
pytz==2016.10
requests==2.12.4
requests-oauthlib==0.7.0
rest-condition==1.0.3
six==1.10.0
tweepy==3.5.0
twilio==5.7.0
uWSGI==2.0.14