Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django-Rest-Framework serializer class meta

as I can use two in a meta model class, when I run it I get an error How I can use the models? It is an example of Django Rest

from rest_framework import serializers
from .models import Post,Miembros

class PostSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = Post
        fields = ('id', 'url', 'titulo', 'contenido','fecha_evento','fecha_evento','banner_grande','lugar')

        model = Miembros
        fields = '__all__'

TypeError at /api/posts/ The fields option must be a list or tuple. Got str. Request Method: GET Request URL: http://127.0.0.1:8000/api/posts/ Django Version: 1.8.3 Exception Type: TypeError Exception Value: The fields option must be a list or tuple. Got str. Exception Location: /home/root-master/restcosolg/cslg/local/lib/python2.7/site-packages/rest_framework/serializers.py in get_field_names, line 900 Python Executable: /home/root-master/restcosolg/cslg/bin/python Python Version: 2.7.6

like image 446
sagoyanfisic Avatar asked Jul 23 '15 18:07

sagoyanfisic


People also ask

What is class Meta in serializer Django?

It serves the same point as using a Meta class object inside a Django model class, or a form class, etc. It's a standard pattern to attach configuration (metadata) to a set of fields that make up the model, form, or in this case, serializer.

What is Django REST framework serializer?

Serializers in Django REST Framework are responsible for converting objects into data types understandable by javascript and front-end frameworks. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.

What is the purpose of class meta?

Model Meta is basically the inner class of your model class. Model Meta is basically used to change the behavior of your model fields like changing order options,verbose_name, and a lot of other options. It's completely optional to add a Meta class to your model.

What is the difference between serializer and model serializer?

The model serializer is just the same as the above serializer in the sense that it does the same job, only that it builds the serializer based on the model, making the creation of the serializer easier than building it normally. So in other words, explicitly defining CRUD methods (get, post,...) is not required.


1 Answers

I know this answer is several years after the question was asked, but I've run into this situation a couple of times. For some reason it's expecting a list instead of a single value.

So if you don't want to use the __all__ value, but you only have 1 value in your model, you need to make sure there is a comma , in the fields section:

class Meta:
        model = Post
        fields = ('id',)
like image 147
Adam Weiler Avatar answered Oct 01 '22 09:10

Adam Weiler