Persisting messages into the database
Let’s enhance the chat application by adding message persistence. We will develop functionality to store messages in the database, allowing us to present a chat history to users when they join a chat room. This feature is essential for real-time applications, where it’s necessary to display both current and previously generated data. For example, consider a stock trading application: upon logging in, users should see not only the current stock values but also the historical values from the time the stock market opened.
To implement the chat history functionality, we will follow these steps:
- We will create Django model to store chat messages and add it to the administration site.
- We will modify the WebSocket consumer to persist messages.
- We will retrieve the chat history to display the latest messages when users enter a chat room.
Let’s start by creating the message model.