0

When I try to do a partial update with patch or a update with put. The object first looks like this:

{
  "name":"Amsterdam 1",
  "location":"Amsterdam",
  "client":"b9c7d1c9-4b1b-4f0d-af30-2d8ffb97647e"
}

Then I remove the client on the object and thus send this back:

{
  "name":"Amsterdam 1",
  "location":"Amsterdam"
}

But this does not remove the client from the object.

The model looks like this:


class FixedLocation(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=155)
    client = models.ForeignKey(Client, on_delete=models.CASCADE, null=True, blank=True)
    location = models.CharField(max_length=263)

And this is how my serializer looks

class FixedLocationSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.FixedLocation
        fields = ["id", "name", "location", "client"]

I expect when I don't send client back that it gets removed from the object. Does anybody know how I can achieve this?

I also tried playing with null and blank on the foreign key.

1 Answers1

0

Try sending the following:

{
  "name":"Amsterdam 1",
  "location":"Amsterdam",
  "client":""
}

This will make your client as blank, which you have enabled in your client field in FixedLocation model. You can even use "client":null to make it null.

If you want to update something, you need to include it. When you do partial update and not include the field you want to update, it will simply ignore the missing field and only update what you have sent in request i.e. you are only sending name and location so only those will be updated and the missing field client will be ignored and will remain as it is.

To know about usage of null and blank check this stackoverflow answer.

To know about usage of partial update check this stackoverflow answer.

isAif
  • 2,126
  • 5
  • 22
  • 34