问题:从一个应用程序到Django中另一个应用程序的外键

我想知道是否有可能在Django的models.py文件中定义外键,该外键引用了另一个应用程序中的表?

换句话说,我有两个应用程序,分别称为cf和profile,在cf / models.py中,我拥有(以及其他功能):

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

并希望在profile / 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

我是通过尝试以这种方式将两个应用程序绑定在一起来违反规则,还是只是语法错误?

I’m wondering if it’s possible to define a foreign key in a models.py file in Django that is a reference to a table in another app?

In other words, I have two apps, called cf and profiles, and in cf/models.py I have (amongst other things):

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

and in profiles/models.py I want to have:

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

But I can’t get it to work. I’ve tried:

    movie = models.ForeignKey(cf.Movie)

and I’ve tried importing cf.Movie at the beginning of models.py, but I always get errors, such as:

NameError: name 'User' is not defined

Am I breaking the rules by trying to tie two apps together in this way, or have I just got the syntax wrong?


回答 0

根据文档,您的第二次尝试应该可行:

要引用在另一个应用程序中定义的模型,必须改为显式指定应用程序标签。例如,如果上述制造商模型是在另一个称为生产的应用程序中定义的,则需要使用:

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

您是否尝试过将其用引号引起来?

According to the docs, your second attempt should work:

To refer to models defined in another application, you must instead explicitly specify the application label. For example, if the Manufacturer model above is defined in another application called production, you’d need to use:

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

Have you tried putting it into quotes?


回答 1

也可以通过类本身:

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

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

It is also possible to pass the class itself:

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

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

回答 2

好的-我知道了。您可以做到,只需使用正确的import语法即可。正确的语法是:

from prototype.cf.models import Movie

我的错误是没有指定该.models行的一部分。天哪!

OK – I’ve figured it out. You can do it, you just have to use the right import syntax. The correct syntax is:

from prototype.cf.models import Movie

My mistake was not specifying the .models part of that line. D’oh!


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。