79199201

Date: 2024-11-18 08:37:52
Score: 1
Natty:
Report link
class PersonSerializer(serializers.ModelSerializer):
    children = serializers.SerializerMethodField()

    class Meta:
        model = Person
        fields = ['id', 'first_name', 'last_name', 'mother', 'father', 'children']

    def get_children(self, obj):
        # Get all children of the demo
        children_as_father = obj.children_as_father.values_list('id', flat=True)
        children_as_mother = obj.children_as_mother.values_list('id', flat=True)
        return list(children_as_father) + list(children_as_mother)

https://www.django-rest-framework.org/api-guide/fields/#serializermethodfield

Reasons:
  • Probably link only (1):
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Low reputation (1):
Posted by: Shenwei Xiao