[Django]-Django Rest framework how to create Family and assign members to that family while assigning roles to each member


You can do all of that in the serializer by using the function create (it would be the same with update, but you are talking here of creation).

class FamilySerializer(serializers.ModelSerializer):
    # No need to define members here as it is the related name
    # and that it will popped out
    class Meta:
        model = Family
        fields = ('id', 'name', 'address', 'monthly_contribution', 'members', 'enabled')
        read_only_fields = ('id',)

    def create(self, validated_data):
        members = None
        if 'members' in validated_data.keys():
            members = validated_data.pop('members')

        # Create the family
        family = Family.objects.create(**validated_data)

        # Deal with members data
        if members is not None:
            for member_data in members:
                role_id = member_data.get('role', None)
                if role_id is not None:
                    role = Role.objects.get(id=role_id)
        return family

The family is created and returned, and the members are created too with the correspondent role.
On the front, it would like that :

        axios.post('api/family/', {
            family_name: 'Smith',
            members: [
                    role: '3' # Father id for example
                    role: '2', # Mother id

You can change of course the role and use the name if you want. Just be careful to be coherent between the field to identify the role in front and back Role.objects.get(field=value)


Leave a comment