Skip to content Skip to sidebar Skip to footer

How Do I Serialize Specific Field In Django Manytomany Field?

So, I'm trying to use Django Rest Framework for my project. I have two models Category and Content to be serialized, as below: views.py class Category(models.Model): category_n

Solution 1:

You need to check out StringRelatedField I think.

https://www.django-rest-framework.org/api-guide/relations/#stringrelatedfield

You can serialize related fields as defined in __str__ method in your model.


And also you can serialize your every item in that field like:

{ id: 1, name: 'category name' }

You need to check nested serializers for done that:

https://www.django-rest-framework.org/api-guide/relations/#nested-relationships

For example:

You need something like nested serializer, you can check it from there:

classCategorySerializer(serializers.ModelSerializer):
    classMeta:
        model = Category
        fields = ("id", "name", ) # You can specify whatever fields you want here.classContentSerializer(serializers.ModelSerializer):
    category = CategorySerializer() # many=True if you wantclassMeta:
        model = Content
        fields = ("id", "category", "body", )

I think what you want is StringRelatedField, return field that yo. The second one, nested relationships was extra

Solution 2:

You can make a read only field in serializer and set the source as follows:

classContentSerializer(serializers.ModelSerializer):
    
    category_name = serializers.CharField(source='category.category_name', 
                    read_only=True)
    classMeta:
        model = Contentfields= [
            'category', 'body', 'created_at',
            ]

You can then bind category_name from JSON response with your frontend.

Post a Comment for "How Do I Serialize Specific Field In Django Manytomany Field?"