Django Data Modeling, E-Commerce Data Modeling, Model Organization in Apps

Introduction to Data Modelling

Models are used to store and retrieve data. First, of all we should always figure out pieces of data that we want to store. So, what entities or concepts do we have in an e-commerce application?

We need a concept of a product with attributes like "title", " description", "price", "inventory". These are dependent on the requirements of the application. Most of the time our products are divided into categories like "shoes," "dresses" and so on... So, we need another entity like "collection". And, an attribute of it called "title". Also, we need to add a relationship between these entities. Thus, we can begin from one end and nevigate to the other end. For example; we can get a collection and then find all the products in that collection.

Sometimes, we can have multiple relationships between two entities.

It is important to note that Django automatically creates an "ID attribute" for us.

Building an eCommerce Data Model

We should always design our models based on the requirements of our project.

hello ilke.png Sometimes, relationship between two entities can have attributes. For example, if a product is in a shopping cart, how many instances of the product we have in shopping cart. So, this relationship itself should have its attribute called quantity.

This is what we call an "Association Class".

bros go,.png

What about the user that owns this cart? Carts are generally anonymous. Anyone can have a shopping cart, it is anonymous or a registered user.

Registered customer should have attributes such a "email", "name", or "password". These customers have orders and each order belongs to one customer. So, we need a one-to-many relationship between customers and orders. But, we should be having many-to-many relationship between orders and products.

Relationships can be explained like this:

relationship.png

Finally, we can have a relationship like this:

deniyorum.png

Organizing Models in Apps

Each app in a Django project provides a specific piece of functionality. Each app is going to have its own data model.

One way to organize our data in is to have a single app called the "store" and drop all the entities here like product, collection, cart, CartItem, Order, OrderItem, Customer... We can bundle and distrubute this app via pip function.

pipenv install

We can just install this app in our project and customize it with code according to our requirements. But, there is a small problem. Because of having a massive amount of data, sometimes app gets hard to maintain. And, we call it a "monolith".

Instead, we can have different apps, do different things. When, each app is self-contained and has zero coupling between apps then, it can work much better.