python - Django custom save method and updating -
i've got custom save() method check object's "active" field equal 2 , give same number descendant fields (using mptt)
def save(self): if self.active == 2: self.get_descendants().update(active=2) super(post, self).save()
now want code work when update() model. should try make custom update method? how it?
an easy fix original update, , using get_queryset_descendants()
additional update descendants. full code this:
qs = <some queryset> qs.update(**values) descendants = mymodel.objects.get_queryset_descendants(qs.filter(active=2)) descendants.update(active=2)
or if want update active
attribute, can done in single go:
qs = <some queryset> descendants = mymodel.objects.get_querset_descendants(qs, include_self=true) descendants.update(active=2)
this can of course wrapped in update
function. this:
from django.db import transaction django.db.models.query import queryset class mymodelqueryset(queryset): def update(self, **kwargs): transaction.atomic(): # django >= 1.6 ####### or ###### transaction.commit_on_succes(): # django <= 1.5 r = super(mymodelqueryset, self).update(**kwargs) descendants = self.model.objects.get_query_set_descendants(self.filter(active=2)) descendants.update(active=2) return r
the with transaction.atomic()
or with transaction.commit_on_succes()
prevents first update saving if second update fails, ensure integrity on database level should go wrong in second update.
you should check documentation current version of django on how use custom queryset custom managers (that mppt.managers.treemanager
).
Comments
Post a Comment