Django 中从一个应用程序到另一个应用程序的外键 [英] Foreign key from one app into another in Django

查看:36
本文介绍了Django 中从一个应用程序到另一个应用程序的外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以在 Django 的 models.py 文件中定义一个外键,作为对另一个应用程序中表的引用?

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?

换句话说,我有两个应用程序,名为 cf 和配置文件,在 cf/models.py 中有(除其他外):

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)

在profiles/models.py中我想要:

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)

而且我试过在models.py的开头导入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?

推荐答案

根据文档,您的第二次尝试应该有效:

According to the docs, your second attempt should work:

要引用在另一个应用程序中定义的模型,您必须明确指定应用程序标签.例如,如果上面的制造商模型是在另一个名为 production 的应用程序中定义的,则您需要使用:

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?

这篇关于Django 中从一个应用程序到另一个应用程序的外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆