Search code examples
pythondjangodjango-rest-frameworkdjango-serializer

Implementing a create function for a Serializer class containing foreignkey


So, this is how i have implemented the class:

class VenueSerializer(serializers.ModelSerializer):
    city = serializers.StringRelatedField(many=True)
    class Meta:
        model = Venue
        fields = '__all__'

    def create(self, validated_data):
        venue = Team(
            name=validated_data['name']
            #I know this is wrong but i just wanted to demonstrate what is it that i need to get done
            #city is the foreign key referencing to the model City
            city=validated_data['city']
        )
        venue.save()
        return venue

So i have a model for venues, and each venue has to be associated with the model city. I am new to the REST Framework and i can't figure out a way to create an instance of the venue model while setting the value of the city field. Can someone please help me with this?

Than you


Solution

  • You can use a PrimaryKeyRelatedField, to add a foreign key relation to the object you are creating:

    class VenueSerializer(serializers.ModelSerializer):
        city = serializers.PrimaryKeyRelatedField(queryset=City.objects.all())
        class Meta:
            model = Venue
            fields = '__all__'
    

    You can pass a request data like this:

    {
        "name": "MyVenue",
        ... (other venue related data)...,
        "city": 1,
    }
    

    where city is a valid foreign key to a City object. This will automatically set the foreign key to the venue object for you, and you don't even need to override create to handle it.