문제

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]
도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top