Error with DRF: the object does not have the model attribute

1

I am trying to create a REST API in my application of v1.9, with

asked by toledano 16.04.2016 в 21:40
source

1 answer

1

After investigating for a while, the problem is that I am using the ViewSet incorrectly.

The serializer

To convert the data to object objects JSON , I am using a ModelSerializer that automatically:

  • generates the set of fields that the model has
  • create validators for the fields or model, such as unique_together
  • includes implementations for .create() and .update()

I must go through this serializer, an object of type Politica , either a queryset or an individual record.

The ViewSet

The ViewSet class generates two kinds of responses, a list and a detail , which are passed through the serializer to get the data in JSON and is here where I have the problem.

In the Politica example, the list is a queryset that contains all the versions of the quality policy, and the detail returns one and only one policy, which is obtained by default of the identifier pk .

And this is my problem: I intend to return a single record in a list. The error that is reported, that expects a queryset and I'm sending a simple object.

If I want a single object in the list I can not use queryset = Politica.objects.latest() that returns an individual object. Instead, you should use queryset = Politica.objects.latest()[:1] that converts the result into a list with a single value.

Conclusion

A ViewSet is excellent for creating an API from a model without any effort.

  

Now that I understand my mistake, I must raise another problem.

    
answered by 17.04.2016 / 17:46
source