Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
124 views
in Technique[技术] by (71.8m points)

python - Foreign key from one app into another in Django

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...