Here is a first cut at identifying the models in SuperBook. Typical to an early attempt, we have represented only the essential models and their relationships in the form of a class diagram:
Let's forget models for a moment and talk in terms of the objects we are modeling. Each user has a profile. A user can make several comments or several posts. A Like can be related to a single user/post combination.
Drawing a class diagram of your models like this is recommended. Some attributes might be missing at this stage but you can detail them later. Once the entire project is represented in the diagram, it makes separating the apps easier.
Here are some tips to create this representation:
The class diagram can be mapped into the following Django code (which will be spread across several apps):
class Profile(models.Model): user = models.OneToOneField(User) class Post(models.Model): posted_by = models.ForeignKey(User) class Comment(models.Model): commented_by = models.ForeignKey(User) for_post = models.ForeignKey(Post) class Like(models.Model): liked_by = models.ForeignKey(User) post = models.ForeignKey(Post)
Later, we will not reference the User
directly but use the more general settings.AUTH_USER_MODEL
instead.
Like most components of Django, a large models.py
file can be split up into multiple files within a package. A package is implemented as a directory, which can contain multiple files, one of which must be a specially named file called __init__.py
.
All definitions that can be exposed at package level must be defined in __init__.py
with global scope. For example, if we split models.py
into individual classes, in corresponding files inside models
subdirectory such as postable.py
, post.py
, and comment.py
, then the __init__.py
package will look like:
from postable import Postable from post import Post from comment import Comment
Now you can import models.Post
as before.
Any other code in the __init__.py
package will be run when the package is imported. Hence, it is the ideal place for any package-level initialization code.