ChatGPT解决这个技术问题 Extra ChatGPT

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?


M
Michael Warkentin

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?


Relevant docs can be found here
Is it okay to have foreign keys across many apps? i am doing a project having many apps with many foreign keys across many apps within a project. fyi, i have already started the question but waiting for answers. stackoverflow.com/questions/55213918/…
Late, I know, but it's mostly a matter of choice and organisation. I have "internal" apps that are not ever intended for external use. They can depend on each other and exist mainly to give me a convenient organisation of my files and namespaces. External apps (eg from DjangoPackages) and apps that I might one day contribute to the public, need to be kept as free as such dependencies as possible (although dependency on some other well-supported public-domain app might be OK. A lot of public user-related apps depend on Django's user/group/permission models).
Thanks, this worked for me. By adding quotes, we don't need to import the class. But I wonder if there are any differences if we decide to import the class, such as the other nice example given by @andorov ?
a
andorov

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)

J
Jan

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!


Sometimes you have to use quotes and not imports, as you may get files importing each other.