Goro
Goro

Reputation: 10249

Is it a good programming practice to separate models from the rest of the application

My project consists of several django applications that need to be deployed differently, possibly on different machines. However often these apps occasionally need to access each other's models, so I was thinking of "externalizing" my models so that they can be accessed more elegantly from any app. So the idea is to do have directory structure resembling something like this:

/ 
+ application1
+ application2
+ models

Is there a functional point to doing that (other than code maintainability), since the applications can cross-reference each other?

Upvotes: 6

Views: 260

Answers (3)

sgallen
sgallen

Reputation: 2109

The following didn't fit well in the comments to @jcollado's answer so I'll put it here:

https://docs.djangoproject.com/en/dev/topics/db/models/#models-across-files

Models across files

It's perfectly OK to relate a model to one from another app. To do this, import the related model at the top of the model that holds your model. Then, just refer to the other model class wherever needed. For example:

from geography.models import ZipCode

class Restaurant(models.Model):
    # ...
    zip_code = models.ForeignKey(ZipCode)

Upvotes: 3

aganders3
aganders3

Reputation: 5955

I don't think this is a particularly good idea, though I can see the appeal. You will be including a lot of models you're not using if you only want one of your apps installed. I think it's best to keep models within the app they most relate to.

This also may make using the admin interface more confusing. Where do you register the models with the admin? Where do you do the admin customization for a model?

Upvotes: 2

jcollado
jcollado

Reputation: 40424

The following paragraph in the django book makes me think that that's probably not a good idea (I added the bold formatting):

However, there’s one requirement regarding the app convention: if you’re using Django’s database layer (models), you must create a Django app. Models must live within apps. Thus, in order to start writing our models, we’ll need to create a new app.

Upvotes: 4

Related Questions