Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through objects in many to many field

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]
like image 965
Gunther Avatar asked Mar 20 '23 16:03

Gunther


1 Answers

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.

like image 170
Gunther Avatar answered Mar 29 '23 13:03

Gunther