直到最后 child,通过关系 运行 最 djangoish 的方式是什么?
What would be the most djangoish way to run through relations until last child?
我正在努力寻找一种有效的方法来处理 Django m2m 关系。
我的用例是:
- 我从表单中收到一个字符串,并用这个字符串更新元素的状态。
- 如果这个元素有 children,我用相同的值更新它们的状态。
- 如果那些 children 元素有自己的 children,那么我会更新状态并检查它们的 children 等 ..
我的模型 m2m 字段如下:parent = models.ManyToManyField('self', blank=True, default=None, symmetrical=False, verbose_name="")
目前我写过这样的东西:
if model == Ensemble:
children = elem.ensemble_set.all()
for child in children:
update_elem_statut(child, statut)
for en in child.ensemble_set.all():
update_elem_statut(en, statut)
if len(en.ensemble_set.all()):
for en_child in en.ensemble_set.all():
update_elem_statut(en_child, statut)
但这绝对不是递归的。我需要遍历每个 children 直到只有 children 元素。我不知道最 pythonish/djangoish 的方法是什么。
在此先感谢您的帮助。
执行此操作的简单方法是向您的模型添加一个方法,该方法对所有当前对象子对象调用相同的方法
class Ensemble(models.Model):
def update_status(self, status):
self.status = status
self.save()
for child in self.ensemble_set.all():
child.update_status(status)
我正在努力寻找一种有效的方法来处理 Django m2m 关系。
我的用例是:
- 我从表单中收到一个字符串,并用这个字符串更新元素的状态。
- 如果这个元素有 children,我用相同的值更新它们的状态。
- 如果那些 children 元素有自己的 children,那么我会更新状态并检查它们的 children 等 ..
我的模型 m2m 字段如下:parent = models.ManyToManyField('self', blank=True, default=None, symmetrical=False, verbose_name="")
目前我写过这样的东西:
if model == Ensemble:
children = elem.ensemble_set.all()
for child in children:
update_elem_statut(child, statut)
for en in child.ensemble_set.all():
update_elem_statut(en, statut)
if len(en.ensemble_set.all()):
for en_child in en.ensemble_set.all():
update_elem_statut(en_child, statut)
但这绝对不是递归的。我需要遍历每个 children 直到只有 children 元素。我不知道最 pythonish/djangoish 的方法是什么。
在此先感谢您的帮助。
执行此操作的简单方法是向您的模型添加一个方法,该方法对所有当前对象子对象调用相同的方法
class Ensemble(models.Model):
def update_status(self, status):
self.status = status
self.save()
for child in self.ensemble_set.all():
child.update_status(status)