My models looks something like this:
class Store:
category = ManyToManyField(Category)
class Category:
parent = ForeignKey(Category)
This is what I want to do:
def update_storem2m_handler(instance, action, reverse=False, pk_set=[], **kwargs):
for c in instance.category.all():
instance.category.add(c.parent)
m2m_changed.connect(update_storem2m_handler, sender=Store.category.through)
But alas it doesn't work. My current solution is the following:
update_storem2m_handler_lock = False #ugly hack to make a lock. NONCONCURRENT!
def update_storem2m_handler(instance,
action="post_add", reverse=False, pk_set=[], **kwargs):
"""If a category is connected, it's parent should be to"""
#should we run this function? probably not
global update_storem2m_handler_lock
if update_storem2m_handler_lock:
return
if reverse:
for p in pk_set:
update_storem2m_handler(Store.objects.get(pk=p),
action, reverse, [instance.pk], **kwargs)
return
if not action in ["post_add"]: #, "post_remove", "post_clear"]:
return
#yes we can run this function
ps=[]
for c in instance.category.all():
ps.append(c)
#remove everything
instance.category.clear()
update_storem2m_handler_lock = True
#and under lock, add everything we want
instance.category.add(*ps)
update_storem2m_handler_lock = False
I have a problem with it though: it is really ugly!!! Anyone have any idea on how to make it nice (and efficient)?