简体   繁体   English

在Django中,通过外键选择相关字段

[英]In Django select related field via foreign key

I am aware of that to select a related object one should do object.related_set.all() . 我知道选择一个相关对象应该做object.related_set.all() Yet in my situation this produces an AttributeError, so it's very hard to debug. 但是在我的情况下,这会产生AttributeError,因此很难调试。 Here is the setup: 这是设置:

class Action(models.Model):
    ...

class FieldDiff(models.Model):
    action = models.ForeignKey(Action, editable=False, related_name='Action')

And in a shell: 并在外壳中:

In [16]: act = Action.objects.get(pk=34)
In [17]: act.fielddiff_set.all()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)

/home/ipantuyev/progs/ccc_app/<ipython console> in <module>()

AttributeError: 'Action' object has no attribute 'fielddiff_set'

I suppose this has to do with translation from camelcase. 我想这与驼峰驼的翻译有关。 I can go around this, but this code would be called from the template, so I would rather have no extra logic. 我可以解决这个问题,但是将从模板中调用此代码,所以我宁愿没有多余的逻辑。

This is because you specified related_name to be Action . 这是因为您将related_name指定为Action This means you want to access all FieldDiff instances associated with an Action via Action_set . 这意味着您想通过Action_set访问与Action关联的所有FieldDiff实例。 Since it seems like this isn't what you want, the simplest solution is to remove the related_name parameter. 由于这似乎不是您想要的,因此最简单的解决方案是删除related_name参数。

This has nothing to do with "translation from camelcase". 这与“从驼峰式翻译”无关。

You have given your ForeignKey an explicit related_name attribute. 您已为ForeignKey提供了显式的related_name属性。 This is the name that Django uses to provide the reverse relationship. 这是Django用于提供反向关系的名称。 So your query should be: 因此,您的查询应为:

act.Action.all()

Actually, that related_name value makes no sense. 实际上,那个related_name值没有任何意义。 You should remove it, then the original fielddiff_set would work. 您应该将其删除,然后原始的fielddiff_set将起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM