django 序列化程序自定义查询集字段

ikfrs5lh  于 12个月前  发布在  Go
关注(0)|答案(1)|浏览(105)

有没有一种方法可以在调用查询集的序列化程序中创建自定义字段?下面是我正在尝试做的事情:
我有一个雇员序列化,我想有“last_attendance”字段包括在内。

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

字符串
我想再添加一个字段“last_attendance”。这是一个像这样的查询集:

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


最新消息:
供您参考,我正尝试在此REST API中使用DataSerializer

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)


最新消息:
我发现这可能是相关的,但还没有弄清楚如何应用Django Rest Framework - How to add custom field in ModelSerializer

q3aa0525

q3aa05251#

使用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

字符串

相关问题