Philip Mutua
Philip Mutua

Reputation: 6891

How do I import multiple classes in another django app correctly

I am using python 3.5 + django 1.11 and I have two apps hr and payroll in my project called ERP.

On payroll app model.py I'm importing classes from hr as below:

# Imports from your apps
from hr.models import (
    # Employee,
    Job,
    JobHistory,
    Department,
    Section,
    Region,
    Country,
    Location,
)

I think this is cumbersome for me considering if in the future I will add more classes to hr I will have to add the same classes as imports above.

Is there a simpler way to import them at once without adding them one by one ?

Upvotes: 2

Views: 933

Answers (1)

Alasdair
Alasdair

Reputation: 308899

If you only use the models in foreign keys/many-to-many/one-to-one fields, then you may not need to import the models at all. Just use a string instead:

class MyModel(models.Model):
    job = models.ForeignKey('hr.Job', ...)

Another option is to import the models directory:

import hr.models as hr_models

Then change the code to use hr_models e.g. hr_models.Job, hr_models.JobHistory.

Finally, you could do a star import, but this is discouraged because it makes it harder to see where models have been imported from.

from hr.models import *

Note that code is written once but read many times, so it's probably worth the extra time to update the imports instead of a star import.

Upvotes: 3

Related Questions