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

时间:2018-02-01 22:05:51

标签: django django-rest-framework django-queryset serializer

有没有办法在调用查询集的序列化程序中创建自定义字段? 这是我想要做的:

我有一个Employee的序列化程序,我希望包含“last_attendance”字段。

 cols_to_convert <- colnames(dt)
 data.table::setDT(dt)[, (cols_to_convert) := lapply(.SD, as.numeric), .SDcols = cols_to_convert ]

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

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

更新:

对于您的信息,我试图在此REST api中使用EmployeeSerializer

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

更新:

我发现SO可能有用,但还没有弄清楚如何应用Django Rest Framework - How to add custom field in ModelSerializer

1 个答案:

答案 0 :(得分:1)

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