Django rest framework serializing many to many field

You will need a TagSerializer, whose class Meta has model = Tag. After TagSerializer is created, modify the PostSerializer with many=True for a ManyToManyField relation: class PostSerializer(serializers.ModelSerializer): tag = TagSerializer(read_only=True, many=True) class Meta: model = Post fields = (‘tag’, ‘text’,) Answer is for DRF 3

Django rest framework nested self-referential objects

Instead of using ManyRelatedField, use a nested serializer as your field: class SubCategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = (‘name’, ‘description’) class CategorySerializer(serializers.ModelSerializer): parentCategory = serializers.PrimaryKeyRelatedField() subcategories = serializers.SubCategorySerializer() class Meta: model = Category fields = (‘parentCategory’, ‘name’, ‘description’, ‘subcategories’) If you want to deal with arbitrarily nested fields you should take a look … Read more

Include intermediary (through model) in responses in Django Rest Framework

How about….. On your MemberSerializer, define a field on it like: groups = MembershipSerializer(source=”membership_set”, many=True) and then on your membership serializer you can create this: class MembershipSerializer(serializers.HyperlinkedModelSerializer): id = serializers.Field(source=”group.id”) name = serializers.Field(source=”group.name”) class Meta: model = Membership fields = (‘id’, ‘name’, ‘join_date’, ) That has the overall effect of creating a serialized value, groups, … Read more

How do I include related model fields using Django Rest Framework?

The simplest way is to use the depth argument class ClassroomSerializer(serializers.ModelSerializer): class Meta: model = Classroom depth = 1 However, that will only include relationships for forward relationships, which in this case isn’t quite what you need, since the teachers field is a reverse relationship. If you’ve got more complex requirements (eg. include reverse relationships, … Read more

Django rest framework, use different serializers in the same ModelViewSet

Override your get_serializer_class method. This method is used in your model mixins to retrieve the proper Serializer class. Note that there is also a get_serializer method which returns an instance of the correct Serializer class DualSerializerViewSet(viewsets.ModelViewSet): def get_serializer_class(self): if self.action == ‘list’: return serializers.ListaGruppi if self.action == ‘retrieve’: return serializers.DettaglioGruppi return serializers.Default # I dont’ … Read more

Django Rest Framework remove csrf

Note: Disabling CSRF is unsafe from security point of view. Please use your judgement to use the below method. Why this error is happening? This is happening because of the default SessionAuthentication scheme used by DRF. DRF’s SessionAuthentication uses Django’s session framework for authentication which requires CSRF to be checked. When you don’t define any … Read more