5. Django models
A Django model is a Python class that describes data resources. In the vast majority of cases, this will be a relational database such as MySQL or Postgres.
A model provides two interlinked pieces of functionality. They provide a way of describing a database, its tables and the relationships between those tables in pure Python code.
We can then use this Python code so your web application can access the data in a logical and understandable fashion in what’s called object-relational mapping.
This example model creates a new Python class which creates a database table. It defines a Person, which has a first_name and last_name:
from django.db import models class Person(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) def __str__(self): return self.name
first_name and last_name are fields of the model. Each field is specified as a class attribute, and each attribute maps to a database column.
The above Person model would create a database table like this:
CREATE TABLE myapp_person ( "id" serial NOT NULL PRIMARY KEY, "first_name" varchar(30) NOT NULL, "last_name" varchar(30) NOT NULL );
You don’t have to declare the Primary Key in the model.
The last part of the model is a method (function in a class) which returns the name of the row.
Another class we could create, which links to the first class using a ForeignKey field:
class Address(models.Model): number = models.IntegerField(null=False, blank=True) street_name = models.CharField(max_length=500, null=False, blank=True) resident = models.ForeignKey(Person, null=True, on_delete=models.SET_NULL)
We’re now in a position that we could use our models within the views that we already have.
If we jumped back to the views.py, simple view to start using our new database about people and their addresses.
Let’s look at a simple view, perhaps we just want to see the information about the first address.
First of all, we’ll create a variable that contains only addresses we know about. We reference the address table, we want the object, and we want every object. We’re only interested in the first address, and in this instance the all method returns a Python list. We can get the first address with the simple pipeline list indexing.
So in views.py add this:
def simple_view(request): addresses = Address.object.all() first_address = address resident_name = str(first_address.resident) html = "<html><head></head><body>Name: "+resident_name+"<br />Address:"+
first_address.street_name+"</body></html>" return HttpResponse(html)
So – the model classes describe database tables, and the class variables describe the columns in that database.
Within our views, then we can use various data retrieval functions to get the data back. We can subset it the way that we want, and then we can access the data that’s in each row of the table one at a time using the class variable names.
Wednesday 20 October 2021, 269 views
Next post: 6. Django templates
Previous post: 4. Django views
Advanced Web Development index
- 38. Writing API tests
- 37. Testing in Django
- 36. Class-based views in the Django REST framework
- 35. Building a RESTful web service in Django
- 34. Introduction to CRUD, REST and APIs
- 33. Refactoring with generic views in Django
- 32. Django validators
- 31. Django forms (2) – using the ModelForm class
- 30. Django forms (1)
- 28. Adding CSS to the template
- 27. Django templating
- 26. Deleting and updating records
- 25. Joins, filters and chaining commands
- 24. Using the ORM in views.py
- 23. Adding to the database by writing a script
- 22. Adding to the database with Django Admin
- 21. Migrations
- 20. ORM – work through example
- 19. An introduction to the Object-Relational Mapper
- 18. Altering the database
- 17. SQL functions and summaries
- 16. SQL Query performance
- 15. Queries and table joins in SQL
- 14. Inserts and queries in SQL
- 13. Good practice in relational database design
- 12. Limitations to database modelling
- 11. Building a database using SQL
- 10. Introduction to PostgreSQL
- 9. How to start writing a new application in Django
- 8. Building a lightweight project
- 7. Django URLs
- 6. Django templates
- 5. Django models
- 4. Django views
- 3. Creating a new hello app
- 2. Creating a new virtual environment
- 1. Setting up Django
Leave a Reply