ajith siva
ajith siva

Reputation: 57

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

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

Upvotes: 2

Views: 1832

Answers (2)

Charnel
Charnel

Reputation: 4432

Update method used for updating multiple objects at one's, where after calling get method you have a single instance. 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:

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

Upvotes: 3

paras chauhan
paras chauhan

Reputation: 787

update method is of a queryset, when you call get on queryset it return object. so you can update object by set a attribute of object.

you can update object as follow:

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

Upvotes: 0

Related Questions