Arvind Kumar
Arvind Kumar

Reputation: 973

Return extra Fields along with model fields in JSON - Django

I am using a Modelserializer to serialize data. In one of the cases, I have to send some extra fields other than model fields to the UI. How can I do that? Below is my code -

My Model -

class Group(models.Model):
    groupID = models.AutoField(primary_key=True, db_index=True)
    groupName = models.CharField(verbose_name="Name", max_length=30)
    sectionID = models.ForeignKey(Section, on_delete=models.PROTECT, db_column='sectionID')

My Serializer -

class GroupSerializer(serializers.ModelSerializer):
    class Meta:
        model = Group
        fields = ['groupID', 'groupName', 'sectionID']

My View -

@api_view(['GET'])
@permission_classes((permissions.IsAuthenticated,))
def getGroupInfo(request):
   groups = models.Group.objects.all()
   for group in groups:
       group.logical_fied = True if <Custom condition>

   serializer = GroupSerializer(groups, many = True)
   return Response(serializer.data)

Expected response on UI

[{
   "groupID":1,
   "groupName":"A",
   "sectionID":1,
   "logical_field":True
}]

Response I am getting

[{
   "groupID":1,
   "groupName":"A",
   "sectionID":1
}]

In my serializer.data, I don't get logical_field on the UI as it is not defined in GroupSerializer. Is there any way to achieve this?

Upvotes: 1

Views: 214

Answers (1)

Florin
Florin

Reputation: 302

from rest_framework.serializers import (ModelSerializer, BooleanField)

class GroupSerializer(ModelSerializer):
 logical_field = BooleanField(default=True)
 class Meta:
    model = Group
    fields = ['groupID', 'groupName', 'sectionID', 'logical_field']

Upvotes: 2

Related Questions