[Answered ]-How to post a model with a foreignkey using django rest framework with only one field?

1๐Ÿ‘

โœ…

I found the solution, here it is i had to provide one serializer to write and the other to read to get all i want :

this serializer is to get the SalleSport by names and use it to read

class NameSalleSportSerialiser(serializers.ModelSerializer):
 
    class Meta:
        model = SalleSport
        fields= ('name',)



class PlanningListSerialiser(serializers.ModelSerializer):
    salle_sport = NameSalleSportSerialiser()
    class Meta:
        model = Planning
        fields= ('name', 'salle_sport')

this is the serializer that i used to create the nested Model ( with Foreignkey )

class PlanningSerialiser(serializers.ModelSerializer):
    salle_id = serializers.PrimaryKeyRelatedField(queryset= SalleSport.objects.all(), source='salle_sport.id')
    class Meta:
        model = Planning

        fields= ('name', 'salle_id')
 

    def create(self, validated_data):
       
        plan = Planning.objects.create(salle_sport=validated_data['salle_sport']['id'], name=validated_data['name'])

        return plan

and in React side i fetched made tow request one GET to retreive all SalleSport instance that displays the names but post the ID and like this the user sees the names.

๐Ÿ‘คmiyou995

0๐Ÿ‘

Try

class PlanningSerialiser(serializers.ModelSerializer):
    salle_sport = SalleSportSerialiser(read_only=False)

    class Meta:
        model = Planning
        fields= ('salle_sport',)
๐Ÿ‘คVJ Magar

Leave a comment