1

Is there a way to create a custom field in a serializer that calls a queryset ? Here is what I am trying to do:

I have a serializer for Employee and I want to have "last_attendance" field included.

class EmployeeSerializer(serializers.ModelSerializer):
    class Meta:
        model = Employee
        fields = ("id", 
                    "username", 
                    "first_name",
                    "last_name")

I would like to add one more field "last_attendance". Which is a queryset like this:

"last_attendance" = Attendance.objects.filter(employee_id = id_of_that_employee).last()

UPDATE:

For your info, Im trying to use EmployeeSerializer in this REST api

queryset = Employee.objects.annotate(fullname=Concat('first_name', Value(' '), 'last_name'))
employee_list = queryset.filter(fullname__icontains=request.POST['search_string'], 
                                company=auth_employee.employee.company.id).order_by('id') 

page = request.GET.get('page', request.POST['page'])
paginator = Paginator(employee_list, request.POST['page_limit'])

try:
    employees = paginator.page(page)
except PageNotAnInteger:
    employees = paginator.page(request.POST['page'])
except EmptyPage:
    employees = []


serializer = EmployeeSerializer(list(employees), many=True)
data = serializer.data[:]
return Response(data, status=status.HTTP_200_OK)  

UPDATE:

I found SO that might be relevant but havent figured out how to apply Django Rest Framework - How to add custom field in ModelSerializer

Axil
  • 3,606
  • 10
  • 62
  • 136

1 Answers1

3

Use MethodField:

class EmployeeSerializer(serializers.ModelSerializer):
    last_attendance = serializers.SerializerMethodField()
    class Meta:
        model = Employee
        fields = ("id", 
                    "username", 
                    "first_name",
                    "last_name",
                    "last_attendance")

    def get_last_attendance(self, obj):
        attendance = Attendance.objects.filter(employee_id = id_of_that_employee).last()
        if attendance:
            return attendance.date  # assuming it has this field
        else:
            return None
Muhammad Hassan
  • 14,086
  • 7
  • 32
  • 54
dukebody
  • 7,025
  • 3
  • 36
  • 61
  • thanks. how do i get this id_of_that_employee ? is it obj.pk ? – Axil Feb 02 '18 at 00:39
  • i'ved got this error. django.core.exceptions.ImproperlyConfigured: Field name `last_attendance` is not valid for model `Employee`.https://gist.github.com/axilaris/5d345064d0174292f535702eed1b2276 – Axil Feb 02 '18 at 00:50
  • i found this related SO https://stackoverflow.com/questions/14583816/django-rest-framework-how-to-add-custom-field-in-modelserializer. not sure if it can be applied. – Axil Feb 02 '18 at 00:51
  • i got it to work like this! https://dpaste.de/1YjT just that missing line. how do i display some fields from attendance, its only able to display one field – Axil Feb 02 '18 at 01:23
  • You need to serialize `Attendance` model data in `get_last_attendance` method. – Muhammad Hassan Feb 02 '18 at 06:11