Home > front end >  How to add a breed to an animal from the available breeds in django rest framework
How to add a breed to an animal from the available breeds in django rest framework

Time:08-03

i am looking how i can assign a breed to an animal upon the creation of an animal for example i have added many breeds to my database and now i want to clean it and assign a breed to each animal for example dogs can have rottweiler, Abradore and more in the rest framework this is how I made my serializer but it makes me create a new breed each time instead of chosing the breed from the available breeds

class AnimalBreedSerializer(serializers.ModelSerializer):
    class Meta:
        model = AnimalBreed
        fields = ("name",)


class AnimalTypeSerializer(serializers.ModelSerializer):
    animal_breed = AnimalBreedSerializer(many=False, read_only=True)

    class Meta:
        model = AnimalBreed
        fields = ("name","animal_breed")

these are my models

class AnimalBreed(models.Model):
    name = models.CharField(max_length=256, unique=True, primary_key=True)


class AnimalType(models.Model):
    name = models.CharField(max_length=256, unique=True, primary_key=True)
    breed = models.ForeignKey(AnimalBreed, on_delete=models.CASCADE)

CodePudding user response:

Ended up solving this by changing the models and serializers with the appropriate fields.

  • Related