Iterate through objects in many areas

I was wondering if it is possible to iterate over the elements in the many_to_many field. My goal was to return a list of items similar to my get_employees method below.

class UserSerializer(serializers.ModelSerializer):
    days_since_joined = serializers.SerializerMethodField('get_days_since_joined')
    employees = EmployeeSerializer(many=True)

    class Meta:
        model = User

    def get_days_since_joined(self, obj):
        return (now() - obj.date_joined).days

    def get_employees:
        return [employee for employee in obj.employees]
+4
source share
1 answer

It was not too far from how it should have been done. What needed to be included in obj.employees.all (), and not just for obj.employees.

.all () is the actual getter method for all objects attached to the model.

+5
source

Source: https://habr.com/ru/post/1539364/