Foreign key from one application to another in Django

I am wondering if it is possible to define a foreign key in the models.py file in Django, which is a link to a table in another application?

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

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

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

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

But I can’t make it work. I tried:

  movie = models.ForeignKey(cf.Movie) 

and I tried to import cf.Movie at the beginning of models.py, but always get errors, for example:

 NameError: name 'User' is not defined 

Am I breaking the rules by trying to link the two applications together this way, or did I just get the syntax wrong?

+61
python django django-models
Nov 27 '08 at 13:24
source share
3 answers

According to the docs, your second attempt should work:

To reference models defined in another application, you must explicitly specify the application label. For example, if the manufacturer model above is defined in another application called production, you will need to use:

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

Did you try to put it in quotation marks?

+103
Nov 27 '08 at 14:27
source share

You can also 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) 
+18
Sep 30 '15 at 15:09
source share

OK - I get it. You can do this, you just need to use the correct import syntax. The correct syntax is:

 from prototype.cf.models import Movie 

My error did not indicate the .models part of this line. D'o!

+8
Nov 27 '08 at 14:26
source share



All Articles