Question

I was wondering if it was possible to iterate through the items in a 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]
Was it helpful?

Solution

This wasn't too far off from how it was suppose to be done. What needed to be included was in obj.employees.all() instead of just obj.employees.

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top