Thiago Bueno
Thiago Bueno

Reputation: 121

Django Rest Framework instancing serializers error

Hello I'm new in DRF Classes

I'm tryng retrieve data from database to JSON in a API, but the data are in a lot of fields a many tables, linked by foreign keys.

I Want pass a id from a data and the API will retrieve all related data with this field.

Like a Join in SQL

I'm doing it creating a serializers and views from my models.

One of my models is:

class ModelPer(ModelMMixin, SQLMixin):
'''Model 
'''
descricao = models.CharField(
    verbose_name = _(u'Descrição'),
    max_length = 250,
    unique = False
)

ativo = models.BooleanField(
    verbose_name= _(u'Ativo'),
    default = False
)

slug = models.SlugField(
    max_length=150,
    unique=True,
    default=uuid.uuid4()
)

My Serializers is:

class PerSerializer(serializers.ModelSerializer):

class Meta:
    model = ModelPer
    fields = ['id', 'descricao']

My View is:

class PerView(APIView):
"""
View that return all forms in app
"""
def get(self, request):
    queryset = ModelPer.objects.all()
    serializer = PerSerializer(queryset)
    print(serializer.data)
    return Response(serializer.data)

But i'm receiving a empty Json, so when i try debug in Django shell i received this:

>>> from per.models import ModelPer
>>> from api_form.serializers import PerSerializer
>>> queryset = ModelPer.objects.all()
>>> serializer = PerSerializer(queryset)
>>> serialzaer.data

ERROR

The serializer field might be named incorrectly and not match any attribute or key on the QuerySet` instance. Original exception text was: 'QuerySet' object has no attribute 'descricao'.

And when i try in terminal check the serializer like:

>>> seriializer

I receive:

PerspectivaSerializer(<QuerySet [<ModelPer: Pespectiva 1>, <ModelPer: Pespectiva 2>, <ModelPer: Pespectiva 3>]>):
id = IntegerField(label='ID', read_only=True)
data_cadastro = DateTimeField(label='Data de Cadastro', required=False)
excluido = NullBooleanField(label='Excluído?', required=False)
data_exclusao = DateTimeField(allow_null=True, label='Data de Exclusão', required=False)
descricao = CharField(label='Descrição', max_length=250)
ativo = BooleanField(required=False)
slug = SlugField(allow_unicode=False, max_length=150, required=False, validators=[<UniqueValidator(queryset=ModelPer.objects.all())>])
usuario_cadastro = PrimaryKeyRelatedField(allow_null=True, label='Usuário que realizou o Cadastro', queryset=User.objects.all(), required=False)
usuario_exclusao = PrimaryKeyRelatedField(allow_null=True, label='Usuário que realizou a exclusão', queryset=User.objects.all(), required=False)

When i check the queryset, its ok!

Someone can help me? Where its my error! Thanks

Upvotes: 1

Views: 118

Answers (1)

JPG
JPG

Reputation: 88439

To serialize a queryset or list of objects instead of a single object instance, you should pass the many=True flag when instantiating the serializer. You can then pass a queryset or list of objects to be serialized

So, use many=True parameter as,

serializer = PerSerializer(queryset, many=True)

Upvotes: 2

Related Questions