Defining Models in Python

Django’s models are written in Python and provide a mapping to the underlying database structure. Django uses a model to execute SQL behind the scenes to return Python data structures—which Django calls QuerySets.

Writing models in Python has several advantages:

  • Simplicity. Writing Python is not only easier than writing SQL, but it’s less error-prone and more efficient as your brain doesn’t have to keep switching from one language to another.
  • Consistency. As I mentioned earlier, SQL is inconsistent across different databases. You want to describe your data once, not create separate sets of SQL statements for each database to which the application will be deployed.
  • Avoids Introspection. Any application has to know something about the underlying database structure. There are only two ways to do that: have an explicit description of the data in the application code, or introspect the database at runtime. As introspection has a high overhead and is not perfect, Django’s creators chose the first option.
  • Version Control. Storing models in your codebase makes it easier to keep track of design changes.
  • Advanced Metadata. Having models described in code rather than SQL allows for special data-types (e.g., email addresses), and provides the ability to store much more metadata than SQL.

A drawback is the database can get out of sync with your models, but Django takes care of this problem with migrations. You’ve already used migrations in Chapter 2 when you created the MyClub application. We’ll be using them again shortly when we create the Event model.

Also note you can introspect an existing database with Django using the inspectdb management command. We’ll be diving deeper into introspecting existing databases in Chapter 16.