Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display all model fields with ModelSerializer?

models.py:

class Car():     producer = models.ForeignKey(Producer, blank=True, null=True,)     color = models.CharField()     car_model = models.CharField()     doors = models.CharField() 

serializers.py:

class CarSerializer(ModelSerializer):      class Meta:         model = Car         fields = Car._meta.get_all_field_names() 

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!

like image 586
Lev Avatar asked May 16 '15 10:05

Lev


People also ask

What is Slug related field?

SlugRelatedField may be used to represent the target of the relationship using a field on the target. For example, the following serializer: class AlbumSerializer(serializers. ModelSerializer): tracks = serializers.

What is Serializers in Django REST framework?

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 meta in serializer Django?

For what purpose is the class Meta: used in the class inside the Django serializers.py file? it tells it the model to use and what fields to serialize ... It serves the same point as using a Meta class object inside a Django model class, or a form class, etc.


1 Answers

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.

class CarSerializer(ModelSerializer):     class Meta:         model = Car 

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:

class CarSerializer(ModelSerializer):     class Meta:         model = Car         fields = '__all__' 
like image 133
Michael B Avatar answered Sep 29 '22 21:09

Michael B