Skip to content
Advertisement

How to display all model fields with ModelSerializer?

models.py:

JavaScript

serializers.py:

JavaScript

So, here I want to use all fields. But I have an error:

Field name producer_id is not valid for model Car.

How to fix that?

Thanks!

Advertisement

Answer

According to the Django REST Framework’s Documentation on ModelSerializers:

By default, all the model fields on the class will be mapped to a corresponding serializer fields.

This is different than Django’s ModelForms, which requires you to specify the special attribute '__all__' to utilize all model fields. Therefore, all that is necessary is to declare the model.

JavaScript

Update (for versions >= 3.5)

The behaviour described above was deprecated in version 3.3, and forbidden since version 3.5.

It is now mandatory to use the special attribute '__all__' to use all fields in the Django REST Framework, same as Django Forms:

Failing to set either fields or exclude raised a pending deprecation warning in version 3.3 and raised a deprecation warning in 3.4. Its usage is now mandatory.

So now it must be:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement