Reputation: 110163
I was reading over the following code, and the models
were structured such that each class/model had a separate file and then it was imported in __init__.py
. For example:
# __init__.py
from service import Service
from note import Note
etc...
# service.py (one example of the imports)
from django.db import models
class Service(models.Model):
#: service provider name (e.g. Hulu)
name = models.CharField(max_length=64, verbose_name="Title Name", unique=True)
def __unicode__(self):
return u'Service id=%s, name=%s' % (self.pk, self.name)
Which way is better practice, to have all models in one models.py
file, or to have one file-per model? I usually keep all my models for an app in one file, and I had never seen the models separated, which is why I'm asking this question.
Upvotes: 0
Views: 1024
Reputation: 239290
If you're talking true "best practice", that would be following the way Django recommends and using just models.py. However, there's a lot of opinion and argument that goes into the this topic. Nevertheless, my recommendations:
If you have a simple app, with only a few models. Stick with the "Django-way" of just a models.py.
If you have a huge app with lots of models and thousands of lines of code, divvying it out is probably better. However, at this point, you should also ask yourself why your app is so huge and if anything can be factored out into auxiliary apps.
Long and short, my personal opinion is that breaking out of the models into separate files is never a good idea. It can in some cases cause problems and I honestly can't see a use case where it's truly justified. Usually, if your app is big enough to warrant doing this, it's actually a sign that you're lumping too much functionality together that would be better delegated out into other apps.
Upvotes: 2
Reputation: 118458
Best practice is to put them in one file. Look at the django source for example.
The reason you've never seen it is because it's practically never done.
If you can justify it somehow then by all means do it, but it's definitely not the recommended structure. People start to explore splitting models when the file gets too large / can be logically separated.
Upvotes: 1