【发布时间】:2020-08-09 18:47:54
【问题描述】:
我对 Python 很陌生,我认为这个问题应该很容易回答。
我的问题简化后是这样的......
我在 File 类 A 和 B 类中有 2 个类。文件中首先定义 A 类,然后定义 B 类。
class A
...
class B
...
我如何通过 A 类访问 B 类?
class A
something = B
class B
somethingElse = A
这是我正在尝试修复的实际代码
class FirstResource(_ModelResource):
class Meta(_Meta):
queryset = First.objects.all()
resource_name = 'first'
allowed_methods = ['get','put']
filtering = {
'a': ALL_WITH_RELATIONS,
'b': ALL_WITH_RELATIONS,
'c': ALL_WITH_RELATIONS,
}
ordering = ['apt']
# this is the line that would fix everything
second = fields.ForeignKey(SecondResource, 'second', null=True, blank=True, default=None, full=True)
...
class SecondResource(_ModelResource):
class Meta(_Meta):
queryset = Second.objects.all()
resource_name = 'second'
execute_methods = ['get', 'post']
filtering = {
'name': ['exact'],
'leader': ['exact'],
}
super = fields.ForeignKey(FirstResource, 'super', null=True, blank=True, default=None, full=True)
leader = fields.ForeignKey(FirstResource, 'leader', null=True, blank=True, default=None, full=True)
...
在 Python 中没有预先声明,我真的不知道如何解决这个问题。 models.py 中的 First 有一个 ForeignKey 为 Second,Second 有 2 个 Foreign Key 为 First。
将 A 移到 B 下面并不能解决问题,因为 B 也需要 A。我没有编写代码,我只是想修复它 - 当我执行“获取”时,我需要返回“第二个”外键用于两个类中的资源。
【问题讨论】:
-
不能将 B 类移到 A 类之上
-
为什么?你能告诉我们实际的代码吗?
-
已编辑,以便您可以看到更多细节 larsks
标签: python django django-models