[Fixed]-Django-Rest-Framework serializer class meta

29👍

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

17👍

Update (5 May 2016):

__all__ value for fields is now supported in ModelSerializer(Thanks @wim for pointing out).

You can also set the fields attribute to the special value '__all__'
to indicate that all fields in the model should be used.

If you only want a subset of the default fields to be used in a model
serializer, you can do so using fields or exclude options, just as you
would with a ModelForm. It is strongly recommended that you explicitly
set all fields that should be serialized using the fields attribute.

This will make it less likely to result in unintentionally exposing
data when your models change.

It seems you are trying to mix Django ModelForm fields attribute with the DRF serializer fields attribute.
In a DRF serializer, __all__ is an invalid value for the fields attribute.

Secondly, you can’t specify multiple models in a Meta class. You will need to use 2 separate serializers and attach them with each other.

For example you can do something like below:

from rest_framework import serializers
from .models import Post,Miembros


class MiembrosSerializer(serializers.ModelSerializer):
    """
    serializer for Miembros model
    """

    class Meta:
        model = Miembros 
        fields = '__all__' # all model fields will be included


class PostSerializer(serializers.HyperlinkedModelSerializer):
    """
    serializer for Post model
    """

    miembros = MiembrosSerializer()

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

Leave a comment