gpt4 book ai didi

Django:如何向后跟随ForeignKey ('self')

转载 作者:行者123 更新时间:2023-12-04 03:14:08 25 4
gpt4 key购买 nike

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

我可以 :
Achievement.objects.get(pk="1").parent_achievement

太好了但是我如何让所有的 child 呢?
Achievement.objects.get(pk="1").parent_achievement_set

不起作用(可能应该在它周围有更多记号),而且我在搜索时没有看到太多内容。

是否可以?陷入SQL?

最佳答案

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

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="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'),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1114976/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com