How can I manually modify models retrieved from the database in Django? -
i wish such following:
people = people.objects.filter(date=date) person = people[0] person['salary'] = 45000
the last line results in error:
object not support item assignment
to debug find easier start working , modify line line until breaks.
i want modify object rendering in template. if try:
person.salary = 45000
there no error trying
print person.salary
immediately afterwards results in original value being printed. update:
in code doing:
people[0].salary = 45000
which doesn't work. reason
person = people[0] person.salary = 45000
does work. thought 2 pieces of code same
looking @ ids, seems when assign entry variable, copy, not original reference:
in [11]: people = people.objects.filter(salary=100) in [12]: person = people[0] in [13]: person.salary = 5000 in [14]: print person.salary 5000 in [15]: people[0].salary out[15]: 100 in [16]: id(people[0]) out[16]: 35312400 in [17]: id(person) out[17]: 35313104
so, let's @ happens in depth. know in django querysets evaluated when need results (lazy evaluation). quote the django documentation:
slicing. explained in limiting querysets, queryset can sliced, using python’s array-slicing syntax. slicing unevaluated queryset returns unevaluated queryset, django execute database query if use “step” parameter of slice syntax, , return list. slicing queryset has been evaluated (partially or fully) returns list.
in particular, looking @ 'django.db.models.query' source code,
def __getitem__(self, k): """ retrieves item or slice set of results. """ # stuff here ... if isinstance(k, slice): qs = self._clone() if k.start not none: start = int(k.start) else: start = none if k.stop not none: stop = int(k.stop) else: stop = none qs.query.set_limits(start, stop) return k.step , list(qs)[::k.step] or qs qs = self._clone() qs.query.set_limits(k, k + 1) return list(qs)[0]
you can see when use slicing, calling __getitem__
method. self._clone
method provide different instance of same queryset. reason getting different results.
Comments
Post a Comment