Django Rest Framework:shell中的serializer.data show {}

时间:2018-06-07 06:52:12

标签: django-rest-framework

serializer.data在python shell中显示 {} 。但是有四个具有一定价值的实例。当我运行django项目时,它会显示 [{},{},{},{}] 。为什么? 我将关注this tutorial,我正在ubuntu 16.04中运行我的项目

这是我的代码。

教程/ settings.py

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'snippets.apps.SnippetsConfig',

代码段/ models.py

from django.db import models
from pygments.lexers import get_all_lexers
from pygments.styles import get_all_styles

LEXERS = [item for item in get_all_lexers() if item[1]]
LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS])
STYLE_CHOICES = sorted((item, item) for item in get_all_styles())


class Snippet(models.Model):
created = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=100, blank=True, default='')
code = models.TextField()
linenos = models.BooleanField(default=False)
language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100)
style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100)

class Meta:
    ordering = ('created',)

serializer.py

from rest_framework import serializers
from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES


class SnippetSerializer(serializers.Serializer):
class Meta:
    model = Snippet
    fields = ('id', 'title', 'code', 'linenos', 'language', 'style')
def create(self, validated_data):
    """
    Create and return a new `Snippet` instance, given the validated data.
    """
    return Snippet.objects.create(**validated_data)

def update(self, instance, validated_data):
    """
    Update and return an existing `Snippet` instance, given the validated data.
    """
    instance.title = validated_data.get('title', instance.title)
    instance.code = validated_data.get('code', instance.code)
    instance.linenos = validated_data.get('linenos', instance.linenos)
    instance.language = validated_data.get('language', instance.language)
    instance.style = validated_data.get('style', instance.style)
    instance.save()
    return instance

代码段/ urls.py

from django.conf.urls import url
from snippets import views

urlpatterns = [
url(r'^snippets/$', views.snippet_list),
url(r'^snippets/(?P<pk>[0-9]+)/$', views.snippet_detail),

0 个答案:

没有答案