python - 如何处理tastypie中的循环导入

标签 python django circular-dependency tastypie

我目前正在开发一个 django-tastypie 网络应用程序。 我有两个 Django 模型:

class Student(models.Model):
  name = models.CharField()

class Course(models.Model):
  name = models.CharField()
  student = models.ForeignKey(Student)

由此,我在两个不同的文件中有两个 Tastypie 资源。 但是我的问题来了。我希望能够从类(class)中过滤学生,从学生中过滤类(class):

from website.api.course import CourseResource

class StudentResource(ModelResource):
  course = fields.ForeignKey(CourseResource, "course")

  class Meta:
    queryset = Student.objects.all()
    resource_name = "student"
    filtering = { "course" : ALL }

from website.api.student import StudentResource

class CourseResource(ModelResource):
  student = fields.ForeignKey(StudentResource, "student")

  class Meta:
    queryset = Course.objects.all()
    resource_name = "course"
    filtering = { "student" : ALL }

当然,我遇到了循环导入问题。我该如何解决?

谢谢!

最佳答案

您不需要在每个模块中导入其他资源。尝试使用字符串作为参数。

class StudentResource(ModelResource):
    course = fields.ForeignKey('website.api.course.CourseResource', "course")

class CourseResource(ModelResource):
    student = fields.ForeignKey('website.api.student.StudentResource', "student")

关于python - 如何处理tastypie中的循环导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19838939/

相关文章:

html - Django 1.11 中表单呈现的性能不佳

python - 在 Python 中使用相互或循环(循环)导入时会发生什么?

c++ - c++上的循环依赖和继承编译错误

python - Python标准库真的是标准的吗?

Python CronTab IOError

python - 条件数据框分组

Python 社交验证 : How to define a different username scheme?

python - 通过 Python 使用 Asterisk 进行调用

具有动态嵌套组件的 Angular 循环依赖项

java - Jython 的 sqlite3 模块