Separating Out Django Models into Different Files
This will be a really quick post since, for whatever reason, I could not find this information out easy on the internet. The only reason I was able to find it is due to my great and good friend, Andres Buritica’s help. Starting a Django project, then an app gives you a models.py which Django expects to house all the models. This does not seem like the best of ideas, so obviously I want to split up the models into their own files in a specific model directory. To accomplish this, you must do two things:
-
Create a meta class for the model with a field “app_label” being set to the name of your app
-
In your init.py file, import that model.
For example, if you started an app by typing out ‘python manage.py startapp foo’, you can delete your models.py file, replace it with a directory named models (what I do), and inside have an init.py and Bar.py files. in Bar.py:
from django.db import models
class Bar(models.Model):
bar = models.TextField(blank=False)
class Meta:
app_label = "foo"
then in init.py:
from Bar import Bar
This also goes for other things specified outside of the Django “norm” I guess? If I wanted to associate Bar with the admin, I create a subdirectory inside my app named admin, and inside it I have BarAdmin.py
from foo.models import Bar
from django.contrib import admin
admin.site.register(Bar)
Inside the init.py for the admin subdirectory, you’d have:
import BarAdmin
Now I could be doing this all wrong but this is the only way I managed to get everything working. If there is a better way to do this, I am all ears. To you Django/Python professionals out there, this may be common knowledge but I am noobing it up right now trying to better learn Python and Django.