Search code examples
python-3.xdjangodjango-modelsdjango-rest-frameworkdjango-serializer

how do I post a foreign key by some other field rather than primary key in django rest framework


I am developing a pet management api and this is what I post to the body when assigning a day of the week to a pet :

{
   "day": "Sunday",
   "pet_name": 2 <-- how to add pet name (rather than the primary key)(this is a foreign key)
}

How do I pass in the pet name which is the foreign key's field rather than the primary key field.


Solution

  • To avoid confusion I would rename the pet_name property of Day to just pet as it is referencing the Pet model.

    class Day(models.Model):
        pet = models.ForeignKey(Pet, on_delete=models.CASCADE, null=True)
    

    In your DaySerializer you can then just use SlugRelatedField to be able to use the pet's name to reference the pet.

    class DaySerializer(serializers.ModelSerializer):
        pet_props = PropsSerializer(read_only=True, many=True)
        pet = serializers.SlugRelatedField(slug_field='name')
    
        class Meta:
            model = models.Day
            fields = ("id", "day", "pet", "pet_props")
    

    The representation of this serializer will put the pet's name as value for the pet field. Also when writing, this allows you to use the pet's name to reference the pet instance which solves the actual issue in your question.

    (You can technically also do pet_name = serializers.SlugRelatedField(slug_field='name'), but I would not do that to avoid confusion.)

    I would recommend putting a unique constraint on your pet's name property though.