- Django Design Patterns and Best Practices
- Arun Ravindran
- 286字
- 2021-06-25 21:32:04
The model hunt
Here is a first cut at identifying the models in SuperBook. As typical for an early attempt, we have represented only the essential models and their relationships in the form of a simplistic class diagram:
An early attempt at the SuperBook 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. Class 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:
- Nouns in your write-up typically end up as entities.
- Boxes represent entities, which become models.
- Connector lines are bi-directional and represent one of the three types of relationships in Django: one-to-one, one-to-many (implemented with Foreign Keys), and many-to-many.
- The field denoting the one-to-many relationship is defined in the model on the Entity-relationship model (ER-model). In other words, the n side is where the Foreign Key gets declared.
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. We are also not concerned about field attributes such as on_delete or primary_key at this stage. We will get into those details soon.
- Modular Programming with Python
- 密碼學原理與Java實現
- Python從小白到大牛
- Offer來了:Java面試核心知識點精講(原理篇)
- 跟小海龜學Python
- 數據庫系統原理及MySQL應用教程
- PyTorch自然語言處理入門與實戰
- Java加密與解密的藝術
- Oracle Database 12c Security Cookbook
- 大學計算機基礎實驗指導
- Flutter跨平臺開發入門與實戰
- Android Wear Projects
- 好好學Java:從零基礎到項目實戰
- Quantum Computing and Blockchain in Business
- JBoss:Developer's Guide