Unless you are creating a simple website, there is little chance of avoiding the need to interact with some form of database when building modern web applications.

    Unfortunately, this usually means you have to get your hands dirty with Structured Query Language (SQL)—which is just about nobody’s idea of fun. In Django, the messy issues with SQL is a solved problem: you don’t have to use SQL at all unless you want to. Instead, you use a Django model to access the database.

    Django’s models provide an Object-relational Mapping (ORM) to the underlying database. ORM is a powerful programming technique that makes working with data and relational databases much easier.

    Most common databases are programmed with some form of SQL, but each database implements SQL in its own way. SQL can also be complicated and difficult to learn. An ORM tool simplifies database programming by providing a simple mapping between an object (the ‘O’ in ORM) and the underlying database. This means the programmer need not know the database structure, nor does it require complex SQL to manipulate and retrieve data (Figure 4-1).

    Chapter 4: Django Models - 图1

    Figure 4-1: An ORM allows for simple manipulation of data without having to write complex SQL.

    In Django, the model is the object mapped to the database. When you create a model, Django executes SQL to create a corresponding table in the database (Figure 4-2) without you having to write a single line of SQL. Django prefixes the table name with the name of your Django application. The model also links related information in the database.

    Chapter 4: Django Models - 图2

    Figure 4-2: Creating a Django model creates a corresponding table in the database.

    In Figure 4-3, a second model keeps track of a user’s course enrollments. Repeating all the user’s information in the yourapp_Course table would be against sound design principles, so we instead create a relationship (the ‘R’ in ORM) between the yourapp_Course table and the yourapp_UserProfile table.

    Chapter 4: Django Models - 图3

    Figure 4-3: Foreign key links in Django models create relationships between tables.

    This relationship is created by linking the models with a foreign key—i.e., the user_id field in the yourapp_Course table is a key field linked to the id field in the foreign table yourapp_UserProfile.

    This is a simplification, but is a handy overview of how Django’s ORM uses the model data to create database tables. We will dig much deeper into models shortly, so don’t worry if you don’t 100% understand what is going on right now. Things become clearer once you have had the chance to build actual models.