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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With