Search code examples
djangosetmodels

Update and save records in a django.db.models.query.QuerySet object?


In django when dealng with model objects consider the following:

>>> x = table.objects.all()
>>> x[0].coulomb1
'hello'
>>>
>>> x[0].coulomb1 = 'goodbye'
>>>
>>> x[0].coulomb1
'hello'

Please can you help me understand how to change this value and save it?

Thanks in advance :)

EDIT: I managed it with:

>>> x
[<table: table object>]
>>> y = x[0]
>>> y
<table: table object>
>>> y.coulomb1 = 'goodbye'
>>> y.coulomb1
'goodbye'
>>> y.save()
>>>
>>> x[0].coulomb1
'goodbye'

Would be nice if someone could explain why it didn't work whilst within the queryset though.

Thanks :)


Solution

  • table.objects.all() is a django.query.QuerySet object. When you run x[0], you actually calls its __getitem__ method.

    You can find its implementation at github.

    Below is a simplified version. I only remove the safety check and slice code.

    def __getitem__(self, k):
        """
        Retrieves an item or slice from the set of results.
        """
        if self._result_cache is not None:
            return self._result_cache[k]
    
        qs = self._clone()
        qs.query.set_limits(k, k + 1)
        return list(qs)[0]
    

    You see, when the queryset is not cached, each time you run queryset[index], it triggers a new sql query and returns a new object.