I cannot seem to cache changes I make to fields of a Django model. I understand that the reason is that I am only ever changing copies of those fields. But I don't know what to do about it.
Consider this trivial example (the real code is much more complex, but I believe this isolates the issue):
models.py:
class Parent(models.Model):
name = models.CharField(blank=True, max_length=BIG_STRING, unique=True)
class Child(models.Model):
name = models.CharField(blank=True, max_length=BIG_STRING, unique=True)
parent = models.ForeignKey("Parent", blank=True, null=True, related_name="children")
Now someplace in my code I create a hierarchy of models and then cache it (using memcached):
view1.py:
parent = Parent(name="parent")
child = Child(name="child1")
parent.save()
child.save()
parent.children.add(child)
cache = caches["default"]
cache.set("my_unique_key", parent)
So far, so good. Elsewhere in my code I retrieve my cached object and make some changes to it and then re-cache it. But those changes are not saved:
view2.py:
cache = caches["default"]
parent = cache.get("my_unique_key")
local_copy_of_child = parent.children.get(name="child1")
local_copy_of_child.name = "child2"
cache.set("my_unique_key", parent)
Obviously the value of parent.children.all()[0].name
is "child1" instead of "child2".
But, in the real code, the location of the instance I want to change is arbitrarily complex (it could be the child of a parent of a parent of parent of a parent, etc.). So at some point I will have to store an instance in a local variable - either the result of a queryset get
or all
. And at that point, I lose my connection to the parent item that I want to re-cache.
Any ideas?
(Note that I do not want to save the changes in a db yet.)