I'm working on a Django project made by a former employee of the company (so I'm refactoring a whole project made by somebody else that didn't follow Django Best Practices), that have two models on different apps using the same tables on database. The City and State tables are used in both apps.
I want to know which is the best way to apply DRY concepts and use only one model for the two apps access these tables.
The two apps are on the project folder and each one has his own models.py
with the following code for city/state:
from django.db import models
from django.contrib.auth.models import User,Group
from django.db.models.signals import post_save
from django.dispatch import receiver
class state(models.Model):
class Meta:
db_table = '"db_property"."state"'
created_at = models.DateTimeField(db_column='created_at')
updated_at = models.DateTimeField(db_column='updated_at')
name = models.CharField(db_column='name',max_length=50)
class city(models.Model):
class Meta:
db_table = '"db_property"."city"'
created_at = models.DateTimeField(db_column='created_at')
updated_at = models.DateTimeField(db_column='updated_at')
name = models.CharField(db_column='name',max_length=50)
state = models.ForeignKey(state,on_delete=models.CASCADE)
Am I missing something?
Put city
and state
in one or other app, or even in their own citystate
app, and import them from the place they are defined. In an app called foo
:
from citystate.models import city, state
In passing, Django models are class
es, and as such one would normally start them with a capital letter: City
and State
. Honoring conventions like this matter: you may not be confused (yet) but you will confuse the heck out of anybody else reading this code, who will think that these things being imported are functions not classes!
An app is not required to have any views, urls, etc. It can be just a place to put common models and their migrations, and maybe some admin classes.