2014-09-09 4 views
0

Django 1.7에서는 상위 모델에서 관련 모델 클래스를 가져 오기 위해 간단한 한 줄짜리 탐색기를 빨리 찾을 수 없었습니다.Django : 상위 모델 클래스에서 관련 모델 클래스 가져 오기

이러한 두 모델은 서로 다른 파일에 있으며 종종 다른 주요 순환 문자 (즉 깨진) 가져 오기를 가져옵니다.

# File: classroom_model.py 
from django.db import models 
class Classroom(models.Model): 
    class_code = models.IntegerField() 

# File: student_model.py 
from classroom_model import Classroom 
class Student(models.Model): 
    classroom = models.ForeignKey(Classroom, related_name="student_set") 

``여기`

이, 욕망이 만드는 @classmethod를 작성, 예를 들어, 교실에서 학생 모델 클래스에 액세스 할 수 있습니다 : 여기

은 간단한 예제 학생 (예를 들어 classroom.create_student (이름)

답변

2

두 가지 방법.

1) 가장 간단한 방법은 직접에서 외래 키 정의에서 참조를 변경하는 것입니다 문자열로 모델을 참조, 예 :

classroom = models.ForeignKey("Classroom") 

다음 가져 오기 라인 제거 :

from classroom_model import Classroom 

2) 다른 방법은 classroom_model.py에서 정의하는 것입니다 :

Student = Classroom.student_set.related.model``` 

이를 그것이 사용되는 방법 내에서 사용됩니다.

관련 문제