[Django]-About 20 models in 1 django app

31đź‘Ť

âś…

“I have at least 20 models” — this is probably more than one Django “app” and is more like a Django “project” with several small “apps”

I like to partition things around topics or subject areas that have a few (1 to 5) models. This becomes a Django “app” — and is the useful unit of reusability.

The overall “project” is a collection of apps that presents the integrated thing built up of separate pieces.

This also helps for project management since each “app” can become a sprint with a release at th end.

👤S.Lott

76đź‘Ť

This is a pretty common need… I can’t imagine wading through a models.py file that’s 10,000 lines long 🙂

You can split up the models.py file (and views.py too) into a pacakge. In this case, your project tree will look like:

/my_proj
    /myapp
        /models
            __init__.py
            person.py

The __init__.py file makes the folder into a package. The only gotcha is to be sure to define an inner Meta class for your models that indicate the app_label for the model, otherwise Django will have trouble building your schema:

class Person(models.Model):
    name = models.CharField(max_length=128)

    class Meta:
        app_label = 'myapp'

Once that’s done, import the model in your __init__.py file so that Django and sync db will find it:

from person import Person

This way you can still do from myapp.models import Person

👤Jarret Hardie

16đź‘Ť

The models are all related so I cant’s
simply make them into separate apps
can I?

You can separate them into separate apps. To use a model in one app from another app you just import it in the same way you would import django.contrib apps.

👤NathanD

5đź‘Ť

Having 20 models in one app might be a sign that you should break it up in smaller ones.

The purpose of a Django app is to have a small single-purpose piece of code, that fits nicelly together.

So, if you had a e-commerce site, you might have a shopping_cart app, a billing app, and so on.

Keep in mind that there is really no problem in apps depending on each other (although it’s always better if they can be decoupled), but you should not have an app doing two very distinct things.

The article Django tips: laying out an application might help you. As always, take everything you read with a grain of salt (including this answer).

0đź‘Ť

You can break up the models over multiple files. This goes for views as well.

👤Albinofrenchy

0đź‘Ť

You can split them into separate files and simply have imports at the top of your main models.py field.

Whether you’d really want to is another question.

👤Oli

Leave a comment