Friday, July 20, 2012

Cross-App model calling in Django


Let's assume we have two apps in our Django's Root directory. Something like this:

setting.py
manager.pt
courses/
    models.py
    views.py
    urls.py
    tests.py
profiles/
    models.py
    views.py
    urls.py
    tests.py
.
.
.
.

Now, you want to connect the models in profiles and courses together. For instance you have a Course model in course-app and a Student model in profiles-app.
The way you can design, will be something like this:





profiles/models.py
class Student(models):
    first_name = .....
    last_name = .... 
    
    course = models.ManyToManyField("courses.Course" , null = True , blank = True , related_name = "student")





courses/models.py
class Course(models.Model):
    name = ....
    date = .... 
 


Attention to "courses.Course" !! The pattern is : [app_name.model_name] . Do NOT use [app_name.models.model_name], or you will get some sort of nasty errors..     
That's it ..

No comments: