Broken view of Django Rest Framework serializer not working

I follow the Django Rest Framework serializer tutorial , but have discovered unusual behavior. If the print (serializer_instance) apparently should print a useful inspection, I can only return this view:

<snippets.serializers.SnippetSerializer object at 0x10220f110>. 

My code seems to match exactly in this tutorial, and I'm using Django 1.7 and Python 2.7. Does anyone know why this might happen?

snippets / serializers.py:

 from django.forms import widgets from rest_framework import serializers from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES class SnippetSerializer(serializers.ModelSerializer): class Meta: model = Snippet fields = ('id', 'title', 'code', 'linenos', 'language', 'style') 

snippets / 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',) 

shell:

 $ python manage.py shell_plus >>> from snippets.serializers import SnippetSerializer >>> serializer = SnippetSerializer() >>> serializer <snippets.serializers.SnippetSerializer object at 0x10220f110> >>> print repr(serializer) <snippets.serializers.SnippetSerializer object at 0x10220f110> 
+5
source share
2 answers

I had the same problem until I realized that I had version 2.4 installed.

Just read the release notes and upgrade to version 3.0

eg. if you are using requirements.txt, change the rest of the frame line to:

 djangorestframework==3.0 

and run

 pip install -r requirements.txt 
+2
source

I believe this is because you are returning a serializer object. To return the actual data, you need to refer to the data attribute:

 print repr(serializer.data) 
0
source

Source: https://habr.com/ru/post/1210133/


All Articles