Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 580
Ben Avatar asked Nov 27 '08 13:11

Ben


People also ask

How do I create a ForeignKey in Django?

To define a relationship between two models, you need to define the ForeignKey field in the model from the Many side of the relationship. In other words, ForeignKey should be placed in the Child table, referencing the Parent table.

Can a model have two foreign keys Django?

Your intermediate model must contain one - and only one - foreign key to the source model (this would be Group in our example). If you have more than one foreign key, a validation error will be raised.

Does Django index foreign keys?

Django automatically creates an index for all models. ForeignKey columns.


2 Answers

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?

like image 103
Michael Warkentin Avatar answered Sep 29 '22 23:09

Michael Warkentin


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) 
like image 25
andorov Avatar answered Sep 29 '22 22:09

andorov