0

I'm building an API with the django rest framework. I have these models:

class Organism(models.Model):
    name = models.CharField(max_length=255)
    address = models.ForeignKey(Address, on_delete=models.CASCADE)
    type = models.ForeignKey(Type, on_delete=models.CASCADE)

class Address(models.Model):
    street = models.CharField(max_length=255, blank=True)

class Type(models.Model):
    name = models.CharField(max_length=255, blank=True)

This is the view for my mode Organism :

class OrganismViewSet(viewsets.ModelViewSet):
    queryset = Organism.objects.all()
    serializer_class = OrganismSerializer
    pagination_class = StandardResultsSetPagination
    filter_backends = (filters.SearchFilter, DjangoFilterBackend)
    filter_class = OrganismFilter
    search_fields = ('name')

And my serializer:

class OrganismSerializer(serializers.ModelSerializer):
    addresse = AddressSerializer()
    type = TypeSerializer()
    class Meta:
        model = Organism
        fields = '__all__'

    def update(self, instance, validated_data):
        // What I should write to do something "elegant"

Let's imagine when I get my Organism, I have:

{
    "address": {
        "id": 1
        "street": "test"
    },
    type: {
        "id": 1,
        "name": "type Organism"
    },
    "name":"TestTest",
}

So I'm trying to update an Organism (I want to change the name of the street but not create a new object AND change the Type which exists in my database) by sending this:

{
    "address": {
        "id": 1
        "street": "new name"
    },
    type: {
        "id": 2,
        "name": "new type"
    }
    "name":"TestTest",
}

And the fact is I don't have the ID of my object in the parameter "validated_data" of the method update. If you guys know how to proceed... Thank you in advance.

Jérémy Octeau
  • 689
  • 1
  • 10
  • 26
  • Is it because the 'id' is not explicitly defined in your model, that calling is_valid() removes the 'id' field? In that case, have you tried defining id=models.serializers.IntegerField(required=False) in the serializer? – DA-- Aug 07 '18 at 08:30
  • Ok, now I have my ID field in my validated_data. Does it exist a mechanism that detects automatically that the ID of the nested object changed and update it in the DB ? Or should I compare it with a if instance.type.id != validated_data.pop('type')['id'] ? Then I do a Type.objects.get(id=xx) and instance.type = new_type and finally instance.save(). I find this very tedious to do. – Jérémy Octeau Aug 07 '18 at 12:01
  • I'm pretty sure it doesn't exist, you have to write you own method. It similar to [this](https://stackoverflow.com/questions/41312558/django-rest-framework-post-nested-objects) question. – DA-- Aug 07 '18 at 19:11

0 Answers0