Mike Biglan MS
Mike Biglan MS

Reputation: 1882

Django: Get related model class from parent model class

In Django 1.7, I couldn't quickly find a simple one-liner to get a related model class from the parent model.

Often these two models are in different files and one already imports the other leading to circular (i.e. broken) imports.

Here's a simple example:

# File: classroom_model.py
from django.db import models
class Classroom(models.Model):
    class_code = models.IntegerField()

# File: student_model.py
from classroom_model import Classroom
class Student(models.Model):
    classroom = models.ForeignKey(Classroom, related_name="student_set")

```

Here, a desire could be to gain access to the Student model class in Classroom, for example, to write a @classmethod that creates students (e.g. classroom.create_student(name).

Upvotes: 0

Views: 365

Answers (1)

Mike Biglan MS
Mike Biglan MS

Reputation: 1882

Two ways:

1) Simplest way is to change the reference in the ForeignKey definition from a direct model reference to a string, e.g.:

classroom = models.ForeignKey("Classroom")

then remove the import line:

from classroom_model import Classroom

2) The other way is to define in classroom_model.py that:

Student = Classroom.student_set.related.model```

This would be used inside a method where it is used.

Upvotes: 2

Related Questions