首页 > python > 在put请求中手动更新django模型实例。django django休息框架

在put请求中手动更新django模型实例。django django休息框架 (manually update django model instance in put request. django django rest framework)

问题

我通过暴露父模型然后搜索room_set来执行put请求的方式因为我需要查看用户是否有权使用与父模型相关的对象。

现在有了这个,我正在努力做一个手动放。

这个put会更像一个补丁,但是当我在我的本地使用PATCH时,CORS策略不喜欢它。所以我说。

所以我对下一步该怎么做有点困惑。如果我在请求中没有任何数据,如何将新值添加到我的对象或忽略我的模型上的属性?

这是模型和放置请求。

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

所以我打印了序列化的数据,我得到了以下内容。看起来它只是一个字典值,如果一个键不存在则设置默认值。

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())

解决方法

试试这个而不是你的 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")


这是你想要的 ?

问题

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())

解决方法

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 ?

相似信息