Search code examples
pythondjangodjango-rest-frameworkputinsert-update

manually update django model instance in put request. django django rest framework


The way I am doing my put request by exposing the parent model and then searching through the room_set becasue I need to see if the user has permissions to mess with the parent models related objects.

now with that away, I am trying to do a manual put.

This put will act more like a patch but the CORS policy doesn't like it when I use PATCH in my local. so I put.

So Im a little confused about what to do next. How do I add the new value to my object or ignore the attribute on my model if I don't have any data on it in the request?

Here is the model and the put request.

class Room(models.Model):
    venue = models.ForeignKey(Venue, on_delete=models.CASCADE)
    name = models.CharField(max_length=100, null=True, blank=True)
    online = models.BooleanField(default=False)
    description = models.CharField(max_length=1000, blank=True, null=True)
    privateroom = models.BooleanField(default=False)
    semiprivateroom = models.BooleanField(default=False)
    seatedcapacity = models.CharField(max_length=10, null=True, blank=True)
    standingcapacity = models.CharField(max_length=10, null=True, blank=True)
    minimumspend = models.PositiveSmallIntegerField(blank=True, null=True)
    surroundsoundamenity = models.BooleanField(default=False)
    outdoorseatingamenity = models.BooleanField(default=False)
    stageamenity = models.BooleanField(default=False)
    televisionamenity = models.BooleanField(default=False)
    screenprojectoramenity = models.BooleanField(default=False)
    naturallightamenity = models.BooleanField(default=False)
    wifiamenity = models.BooleanField(default=False)
    wheelchairaccessibleamenity = models.BooleanField(default=False)
    cocktailseatingseatingoption = models.BooleanField(default=False)
    classroomseatingoption = models.BooleanField(default=False)
    ushapeseatingoption = models.BooleanField(default=False)
    sixtyroundseatingoption = models.BooleanField(default=False)
    boardroomseatingoption = models.BooleanField(default=False)
    theaterseatingoption = models.BooleanField(default=False)
    hallowsquareseatingoption = models.BooleanField(default=False)




 def put(self, request, *args, **kwargs):
        venuepk = kwargs.get('venuepk', None)
        venue = get_object_or_404(Venue, pk=venuepk)
        roompk = kwargs.get('roompk')
        venuerooms = Venue.room_set.all()
        roomobject = None
        for room in venuerooms:
            if room.pk == int(roompk):
                roomobject = Room.objects.get(pk = roompk)
                serialized = RoomSerializer(request.data)
                if serialized.is_valid(raise_exception=True):
                    data = serialized.validated_data
                    roomobject

so I printed the serialized data and I got what is below. Looks like its nothing more than a dictionary value and setting a default if a key doesn't exist.

RoomSerializer(data={u'minimumspend': None, u'seatedcapacity': 50, u'standingcapacity': 65, u'name': u'The Dean', u'privateroom': u'privateroom'}):
    id = IntegerField(label='ID', read_only=True)
    name = CharField(allow_blank=True, allow_null=True, max_length=100, required=False)
    online = BooleanField(required=False)
    description = CharField(allow_blank=True, allow_null=True, max_length=1000, required=False)
    privateroom = BooleanField(required=False)
    semiprivateroom = BooleanField(required=False)
    seatedcapacity = CharField(allow_blank=True, allow_null=True, max_length=10, required=False)
    standingcapacity = CharField(allow_blank=True, allow_null=True, max_length=10, required=False)
    minimumspend = IntegerField(allow_null=True, max_value=32767, min_value=0, required=False)
    surroundsoundamenity = BooleanField(required=False)
    outdoorseatingamenity = BooleanField(required=False)
    stageamenity = BooleanField(required=False)
    televisionamenity = BooleanField(required=False)
    screenprojectoramenity = BooleanField(required=False)
    naturallightamenity = BooleanField(required=False)
    wifiamenity = BooleanField(required=False)
    wheelchairaccessibleamenity = BooleanField(required=False)
    cocktailseatingseatingoption = BooleanField(required=False)
    classroomseatingoption = BooleanField(required=False)
    ushapeseatingoption = BooleanField(required=False)
    sixtyroundseatingoption = BooleanField(required=False)
    boardroomseatingoption = BooleanField(required=False)
    theaterseatingoption = BooleanField(required=False)
    hallowsquareseatingoption = BooleanField(required=False)
    venue = PrimaryKeyRelatedField(queryset=Venue.objects.all())

Solution

  • try this instead of your put()

    def put(self, request, *args, **kwargs):
        venuepk = kwargs.get('venuepk', None)
        if not venuepk:
            return Respose("venuepk is empty")
        venue = get_object_or_404(Venue, pk=venuepk)
        room = venue.room_set.all().get(id=int(roompk))
        # lets assume that you have to update different fields on different requests
        # So make a  'dict' that has 'key' same as in your `Room` model as below
        update_dict = {
            "description":"some description",
            "online":True,
            "minimumspend":10
        }
        room.update(**update_dict)
        return Response("updated")
    


    Is this what you are looking for ?