简体   繁体   English

异常值:“用户”object 在 DJANGO ORM 中没有属性“更新”

[英]Exception Value: 'User' object has no attribute 'update' thrown in DJANGO ORM

I couldn't figure what is wrong with below statement, I am getting 'User' object has no attribute 'update' thrown in DJANGO ORM我不知道下面的语句有什么问题,我得到 'User' object has no attribute 'update' throw in DJANGO ORM

if "device_id" in request_data:
        try:
            User.objects.get(device_id=request_data["device_id"]).update(device_id=None)
        except ObjectDoesNotExist:
            pass

update method is of a queryset, when you call get on queryset it return object. update 方法是一个查询集,当您在查询集上调用 get 时,它会返回 object。 so you can update object by set a attribute of object.因此您可以通过设置 object 的属性来更新 object。

you can update object as follow:您可以更新 object 如下:

if "device_id" in request_data:
    try:
       u = User.objects.get(device_id=request_data["device_id"])
       u.device_id=None
       u.save()
    except ObjectDoesNotExist:
        pass

Update method used for updating multiple objects at one's, where after calling get method you have a single instance.用于一次更新多个对象的更新方法,在调用get方法后,您有一个实例。 Replace this:替换这个:

User.objects.get(device_id=request_data["device_id"]).update(device_id=None)

with this:有了这个:

user = User.objects.get(device_id=request_data["device_id"])
user.device_id = None
user.save()

Or even better would be to allow device_id field (which I think is ForeignKey) to be null:或者更好的是允许device_id字段(我认为是 ForeignKey)为 null:

# your model class defenition
...
device = models.ForeignKey('on_device_model', null=True, blank=True, on_delete=models.deletion.DO_NOTHING)
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM