[Django]-Create method for foreign key relationships with Django Rest Framework serializers

12👍

Yes, you are doing much more work than you need to.

You should define your fields using SlugRelatedField to allow DRF to automatically populate them from a field on the related model. So:

class FirewallPolicyCreateSerializer(serializers.ModelSerializer):
    team = serializers.SlugRelatedField(queryset=Team.objects.all(), slug_field='name')
    source_ip = serializers.SlugRelatedField(queryset=IP.objects.all(), slug_field='source_ip')
    destination_ip = serializers.SlugRelatedField(queryset=IP.objects.all(), slug_field='destination_ip')

    class Meta:
        model = Policy
        fields = ['id', 'name', 'team', 'source_ip', 'destination_ip']

Now you shouldn’t need to define validate or create at all, as DRF will do all the relevant validation and assignment.

(Note, you didn’t need to redefine the name field either, as you’re not changing anything from the underlying model field.)

Leave a comment