Django:如何向后跟随ManyToMany('self') [英] Django: How to follow ManyToMany('self') backwards

查看:49
本文介绍了Django:如何向后跟随ManyToMany('self')的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class c(models.Model):
    f = models.ManyToManyField(
        'self', 
        blank=True, 
        null=True, 
        related_name='child_set'
    )

我可以做到:

 c.objects.get(pk="1").f

但是我如何通过'_set'来获得?

But how do I get by '_set'?

 c.objects.get(pk="1").child_set

不起作用

我需要这个:

{name:A,parent:[]}
{name:B,parent:[A]}
{name:C,parent:[A,B]}

C.parent.all() == [A,B]
A.parent_set.all() == [B,C]

推荐答案

对于引用selfManyToManyField,不会创建反向关系.这是因为它没有用-它会包含所有引用自己的关系-正向关系会这样做.

For ManyToManyFields that reference self, a reverse relationship is not created. This is because it has no use - it would contain all relations that refer to itself - which is what the forward relation does.

无论您说什么related_name,都应该将其设置为%(field)s_rel_+(结尾的+会阻止创建关系).

You'll find regardless of what you say the related_name should be it will be set to %(field)s_rel_+ (the trailing + prevents the relation being created).

所以答案是没有child_set,因为您可以使用f.

So the answer is there is no child_set because you can just use f.

这篇关于Django:如何向后跟随ManyToMany('self')的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆