Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to choose specific columns when using depth in serializer

I have a model which consists of two ForeignKeys. I am only interested in parsing the content of the ForeignKeys, so i'm using the depth variable, which basically gives me all columns of the tables referenced with the FK. Is there a way to select which columns there should be included?

class SomeSerializer(serializers.ModelSerializer):
    class Meta:
        model = MyAwesomeModel
        fields = ('id', 'fk_one','fk_two')
        depth = 1
like image 493
JavaCake Avatar asked Nov 25 '25 15:11

JavaCake


1 Answers

Try using nested serializers. Documentation here.

Example:

class FKOneSerializer(serializers.ModelSerializer):
    class Meta:
        model = FKOne
        fields = ('name', 'id')

class SomeSerializer(serializers.ModelSerializer):
    fk_one = FKOneSerializer()

    class Meta:
        model = MyAwesomeModel
        fields = ('id', 'fk_one','fk_two')

EDIT:

Similar answer here by the creator of the Django Rest Framework. Also includes some related notes, including that nested serializers are read-only and that you may need to include a source argument on the serializer field.

like image 67
Alex Avatar answered Nov 27 '25 08:11

Alex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!