I
I
Ilya Chichak2017-09-22 07:48:07
Django
Ilya Chichak, 2017-09-22 07:48:07

How to manage Django Rest Framework serializer field?

# models.py:

class SomeModel(models.Model):
    name = models.CharField(max_length=100)
    can_use_all = models.BooleanField(default=False)

class RelatedModel(models.Model):
    parent = models.ForeighKey('SomeModel', related_name='related_obj')
    data = models.TextFields()

# serializers.py
class RelatedSerializer(serializers.ModelSerializer):
    class Meta:
        model = RelatedModel
        fields = '__all__'

class SomeSerializer(serializers.ModelSerializer):
    related_obj = RelatedSerializer(many=True, read_only=True)
    
    class Meta:
        model = SomeModel
        fields = '__all__'

How to make it so that if SomeModel has can_use_all == True, the SomeSerializer serializer has all the RelatedModel objects in the related_obj field, and not just those that point to this object?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya Chichak, 2017-12-18
@ilya_chch

As it turned out, the easiest and most reliable way is to make a second serializer that would give all objects. and in the view, override the get_serializer method, which would slip the desired serializer

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question