chapter four

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 is 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. Hard-coding 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. A lot of websites store and display data that is specific to that site. A movie site has data for movies, a book site has data for books. For Nicky’s RiffMates site you need:

  • Musicians
  • Bands
  • Classifieds
  • Venues
  • Venue Line-ups

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 lookups

4.5 Modifying your data

4.6 Querying models in views

4.6.1 Using URL arguments