code

Django의 한 앱에서 다른 앱으로의 외래 키

codestyles 2020. 9. 16. 07:44
반응형

Django의 한 앱에서 다른 앱으로의 외래 키


Django의 models.py 파일에서 다른 앱의 테이블에 대한 참조 인 외래 키를 정의 할 수 있는지 궁금합니다.

즉, cf와 profiles라는 두 개의 앱이 있고 cf / models.py에는 다른 것들이 있습니다.

class Movie(models.Model):
    title = models.CharField(max_length=255)

및 profiles / models.py에서 다음을 갖고 싶습니다.

class MovieProperty(models.Model):
    movie = models.ForeignKey(Movie)

그러나 나는 그것을 작동시킬 수 없습니다. 난 노력 했어:

    movie = models.ForeignKey(cf.Movie)

models.py 시작 부분에서 cf.Movie 가져 오기를 시도했지만 항상 다음과 같은 오류가 발생합니다.

NameError: name 'User' is not defined

이런 식으로 두 개의 앱을 연결하여 규칙을 위반하고 있습니까? 아니면 구문이 잘못 되었습니까?


문서에 따르면 두 번째 시도는 효과가 있습니다.

다른 애플리케이션에 정의 된 모델을 참조하려면 애플리케이션 레이블을 명시 적으로 지정해야합니다. 예를 들어 위의 제조업체 모델이 프로덕션이라는 다른 애플리케이션에 정의 된 경우 다음을 사용해야합니다.

class Car(models.Model):
    manufacturer = models.ForeignKey('production.Manufacturer')

따옴표에 넣어 보셨습니까?


클래스 자체를 전달할 수도 있습니다.

from django.db import models
from production import models as production_models

class Car(models.Model):
    manufacturer = models.ForeignKey(production_models.Manufacturer)

좋아-알아 냈어. 할 수 있습니다 import. 올바른 구문 을 사용해야 합니다. 올바른 구문은 다음과 같습니다.

from prototype.cf.models import Movie

내 실수는 .models그 줄 일부를 지정하지 않았습니다 . 오!

참고 URL : https://stackoverflow.com/questions/323763/foreign-key-from-one-app-into-another-in-django

반응형