2

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

1
  • Can you share your models and request data? Commented Aug 22, 2021 at 6:12

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.