Skip to content Skip to sidebar Skip to footer

How Assign Existing, Nested Objects In Serializer?

I've got Membership class which contains 3 ForeginKey fields. These FK always have to reference to already existing objects so I'm wondering how simplify create and update methods

Solution 1:

You should be able to pass the arguments directly into the Membership.objects.create call:

def create(self, validated_data):
    return Membership.objects.create(
        **validated_data,
        user_id=validated_data.pop('user'),
        club_id=validated_data.pop('club'),
        inClubRole_id=validated_data.pop('inClubRole')
    )

I believe you can also get this to work by setting your fields as:

fields=('user_id', 'club_id', 'inClubRole_id')

and changing your JSON to:

{"user_id":1,"club_id":1,"inClubRole_id":4}

Solution 2:

I've already handled with it a little bit different. I swapped ...Serializer fields to PrimaryKeyRelatedField so I'm able to update and create Membership object only using IDs of related objects. I also override to_representation(self,value) method so on get reuqests I can fill related fields with nested data. Here's my final solution:

classMembershipSerializer(serializers.ModelSerializer):

user = serializers.PrimaryKeyRelatedField(queryset = User.objects.all())
club = serializers.PrimaryKeyRelatedField(queryset = Club.objects.all())
inClubRole = serializers.PrimaryKeyRelatedField(queryset = InClubRole.objects.all())
classMeta:
    fields=(        
        'user',
        'club',
        'inClubRole',
       )        
    model = Membership

def to_representation(self, value):
    data = super().to_representation(value)  
    user_data = UserSerializer(value.user)
    club_data = ClubSerializer(value.club)
    inClubRole_data = InClubRoleSerializer(value.inClubRole)
    data['user'] = user_data.datadata['club'] = club_data.datadata['inClubRole'] = inClubRole_data.datareturndata

Post a Comment for "How Assign Existing, Nested Objects In Serializer?"