Django Rest framework, how to include '__all__' fields and a related field in ModelSerializer ?


I have two models, one with M2M relation and a related name. I want to include all fields in the serializer and the related field.

class Pizza(models.Model):
    name = models.CharField(max_length=50, unique=True)
    toppings = models.ManyToManyField(Topping, null=True, blank=True, related_name='pizzas')

class Topping(models.Model):
    name = models.CharField(max_length=50, unique=True)
    price = models.IntegerField(default=0)

class ToppingSerializer(serializers.ModelSerializer):
    class Meta:
        model = Topping
        fields = '__all__' 

This works but it doesn’t include the related field.

 fields = ['name', 'price', 'pizzas'] 

This works exactly as I want, but what happens when Toppings model has a lot of fields. I want to do something like :

fields = ['__all__', 'pizzas']

This syntax results in an error saying:

Field name __all__ is not valid for model

Is there a way to achieve the wanted behavior? Or the fields must be typed manually when using a related name ?


I just checked the source code of Django Rest Framework.
The behaviour you want seems not to be supported in the Framework.

The fields option must be a list, a tuple or the text __all__.

Here is a snippet of the relevant source code:

    ALL_FIELDS = '__all__'
    if fields and fields != ALL_FIELDS and not isinstance(fields, (list, tuple)):
        raise TypeError(
            'The `fields` option must be a list or tuple or "__all__". '
            'Got %s.' % type(fields).__name__

You cannot add ‘all‘ additionally to the tuple or list with fields…

Answered By – DanEEStar

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published