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

问题描述

class Achievement(MyBaseModel):
parent_achievement = models.ForeignKey('self',blank = True,null = True,help_text =必须在之前完成的成就这个被实现了)#从父保留的长名称

我可以做:

  Achievement.objects.get(pk =1)。parent_achievement 

这是非常好的。但是如何获得所有的孩子?

  Achievement.objects.get(pk =1)。parent_achievement_set 

不工作(可能应该有更多的符号),我没有看到太多搜索时。



可以吗?

解决方案

默认情况下,django将调用相反的模型名称,后跟_set,因此它将be

  Achievement.objects.get(pk =1)。achievement_set 

如果这不适合您,请使用 related_name 可选参数 models.ForeignKey

  class Achievement(MyBaseModel):
parent_achievement = models。 ForeignKey(
'self',
blank = True,
null = True,
help_text =在此之前必须完成的成就,
related_name =child_achievement_set
)从父保留的长名称

Achievement.objects.get(pk =1)child_achievement_set


class Achievement(MyBaseModel):
    parent_achievement = models.ForeignKey('self', blank=True, null=True, help_text="An achievement that must be done before this one is achieved") # long name since parent is reserved

I can do :

Achievement.objects.get(pk="1").parent_achievement

which is great. But how do I get all the children?

Achievement.objects.get(pk="1").parent_achievement_set

doesn't work (and probably should have some more notation around it), and I didn't see too much when searching.

Is it possible? Fall into SQL?

解决方案

By default, django will call the reverse the model name, followed by "_set", so it would be

Achievement.objects.get(pk="1").achievement_set

If that doesn't suit you, use the related_name optional argument to models.ForeignKey:

class Achievement(MyBaseModel):
    parent_achievement = models.ForeignKey(
        'self', 
        blank=True, 
        null=True, 
        help_text="An achievement that must be done before this one is achieved",
        related_name="child_achievement_set"
    ) # long name since parent is reserved

Achievement.objects.get(pk="1").child_achievement_set

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

09-27 02:32