开发者

Complex Django filter question

开发者 https://www.devze.com 2022-12-26 19:51 出处:网络
Lets say I have this class (simplified): class Tag (...): children = models.ManyToManyField(null=True, symmetrical=False)

Lets say I have this class (simplified):

class Tag (...):
    children = models.ManyToManyField(null=True, symmetrical=False)

Now I already implemented the functions get_parents, get_all_ancestor开发者_开发百科s. Is there a nice pythonic way to just the top level tags? If I had designed my Tags differently (to point to the parents instead) I would just make get_all_parents().filter(children=None).

My first thought is to create a new function that will go recursively through all parents and save those that has none.

But is there a possibility with filters or Query-objects to do the same (with fewer lines of code)?

Thanks for your help.

[edit]

When it is finished, it should be a hierarchical tagging system. Each tag can have children, parents, but only the children are saved. I want to get all the top level tags, that point through many children / childrens children to my tag.


Since you've got symmetrical=False, I think this should work to get all tags with no parents:

Tag.objects.filter(tag_set=None)

I must say though that a ManyToMany relationship is not ideal for a hierarchical system. Usually, an element can only have one parent but multiple children - ie it's a ForeignKey from child to parent. The way you have it, each element can have multiple parents and multiple children, so I don't see how a hierarchical relationship is possible.

As always, I recommend django-mptt to manage hierarchical data.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号