4 Django ORM

 

This chapter covers

  • Interacting with a database through the Django ORM
  • Creating objects that map to database tables
  • Querying the database
  • Building object relationships
  • Loading and storing content through fixtures

This chapter introduces you to Django’s object relational mapping (ORM), an object-oriented abstraction for interacting with databases. Django provides a way to create, read, update, and delete both data and tables in a database to add storage capabilities to your website.

4.1 Interacting with a database

Until now, RiffMates has been composed of mostly static content. You learned how to write views that are called when a user visits a URL, and inside those views, you created small dictionaries to provide context for rendering templates. Hardcoding data dictionaries in a view is rather limited. Most websites have a storage layer that is queried inside the view. Storage gets used for

  • User accounts
  • Inventory
  • E-commerce transactions
  • Experience customization
  • User-created content
  • Site data

If the phrase site data seems vague to you, that’s because it is. Many websites store and display data that is specific to that site. For example, a movie site has data for movies, and a book site has data for books. For Nicky’s RiffMates site you need

  • Musicians
  • Bands
  • Classifieds
  • Venues
  • Venue lineups

4.2 ORM Models

4.3 SQLite and dbshell

4.4 Model queries

4.4.1 Using .all() and .filter() to fetch QuerySet results

4.4.2 Field look-ups

4.5 Modifying your data

4.6 Querying models in views

4.6.1 Using URL arguments

4.6.2 Listing pages

Summary