Database Modelling
Data is the center of the most web applications.
1. Working with Models
Storing data in a database is a common practice in most web applications. In a Django project, it
involves working with Django models. Django will turn these models into database table for us.
Model – a model contains the fields and behaviors of the data we want to store. Commonly each models
maps a database table.
Django models are defined as standard python classes with the wealth of additional features added in
automatically. Behind the scenes ORM allows these classes and their instances have access to the
database. If it were not for the ORM a user could be required to interact with the database directly using
a Structured Query Language(SQL).
Class meta configuration options;
Abstract – a boolean that indicates whether the model was defined as abstract
App_label – a string containing the name that Django uses to recognize the application where the
models were defined.
Db_table – the name of the database that django will use to store and retrieve data for the model
Get_latest_by – used to determine the most recent instance of a model.
Order_with_respect_to – an instance of a field relating to another model.
Ordering – a tuple containing the names of the fields when ordering an instance of a model.
Permissions – a tuple of permissions to be added to the model.
Unique_together – a sequence of tuples indicating any groups that must, when combined be used as
one record in the database
Verbose_name – displays the name of a single instance of a model
Verbose_name_plural – displays name for multiple instance of a model
Verbose_name_raw – for caching
Accesing the Model Cache
Once models have been processed by ModelBase metaclass, they are stored in a global registry called
Appcache contained in django.db.models.loading
How does django processes Model classes?
- Meta classes : - responsible for processing model definitions I the ModelBase which leaves in
django.db.models.base
- Abstract models vs inherited models
1. Django models basics
- Each model is a class that extends django.db.models.Model
- Each model attribute represents a database column
Django.db – this module helps to define and map the characteristic of the model to the database.
Model properties/ model types
Common field attributes
Attname – the name of the attribute on the model instance where the database related value is
stored.
Blank – a Boolean indicating whether the field must have a value supplied
Choices – a sequence of 2 tuples indicating valid choice for a field.
Column – the name of the database column that will be used to hold the fields value
Db_column - The name explicitly supplied as the database column name for the field’s values.
Db_index - A Boolean indicating whether the field was declared to have an index created for it in
the database.
Default – the default value
Description – a simple text description of the field or its purpose
Editable - A Boolean indicating whether the field should be presented to users for editing when
generating forms based on the model.
Empty_strings_allowed - A Boolean indicating whether the field allows an empty string as a
possible value.
Help_text - The informative text provided in the field definition, to be displayed to users when
the field is presented for editing.
Max_length - The maximum length the field’s value can contain.
Name - The name of the field, as defined when assigning the field to the model.
Null - A Boolean indicating whether the field can be committed to the database without a value
assigned.
Primary_key - A Boolean indicating whether the field should be used as the primary key for the
database table.
Rel - In the case of fields that relate one model to another, this will be a special object describing
the various aspects of that relationship.
Serialize - A Boolean indicating whether the field should be included when model instances are
serialized using the serialization framework.
Unique - A Boolean indicating the field must be unique among all instances of the model.
Unique_for_date - The name of a date-related field, such as a DateField or DateTimeField, for
which this value should be unique.
Unique_for_month - Like unique_for_date, except that the uniqueness is only required for
objects that occur within the same month
Unique_for_year - Like unique_for_date, except that the uniqueness is only required for objects
that occur within the same year.
Verbose_name - The full name of the field, in plain English, to be displayed to users.
Common field methods
Clean(value, instance) - Validates the given value is appropriate for the model, and the instance
it's assigned to.
Contribute_to_class(cls, name) - Configures the field for the class it’s attached to.
Dd_type(connection) - Returns the database-specific column definition necessary for this field
to store its data.
Form_field() - Returns a form field based on the field’s data type and verbose name, suitable for
inclusion on any standard form.
Get_attname() - Returns the name that should be used for the attname attribute.
Get_attname_column() - Returns a two-item tuple containing the values to be used for the
attname attribute as well as the column attribute.
Get_cache_name() - Returns a name suitable for use as a cache for the field, if caching is
necessary.
Get_choices() - Returns a sequence of 2-tuples that should be used for displaying choices to
users looking to enter data into this field.
get_db_prep_lookup(value, lookup_type, connection, prepared=False) - Returns a
representation of the supplied value that’s suitable for comparing against existing values in the
database
get_db_prep_save(value, connection) - Returns a representation of the supplied value that’s
suitable to be stored in the database.
Get_db_prep_value(value, connection , prepared=False) - Returns a representation of the
supplied value that’s ready for general use with the database.
Get_default() – Returns the default value that would be used for the field.
Has_default() - Returns True if the field has a default value associated with it, or False if the
default behavior will be left to the database backend.
Pre_save(model_instance, add) - Returns a value for the field just prior to being saved in the
database.
Save_form_data(instance, data) - Stores the supplied data to the appropriate attribute on the
supplied instance.
To_python(value) – Coerces the supplied value to a native python data type that can be used
when accesing the fields value on a model instance
Validate(value, instance) - Returns without error if the field’s value is appropriate for the field’s
configuration and other data on a model instance, or raises django.core.exceptions.
ValidationError otherwise. This is called internally by clean().
Field Types
AutoField
BigIntegerField
BooleanField
CharField
CommaSeparatedIntegerField
DateField
DateTimeField
DecimalField
FileFiled
FilePathField
FloatField
ImageField
IntegerField
IPAddressField
NullBooleanField
OneToOneField
PositiveIntegerField
PositiveSmallIntegerField
SlugField
SmallIntegerField
TextField
TimeField
CharField – is a string for small-to-large-sized strings, max_length argument is required
2. Installing Pillow and Image Configuration – adds image processing capabilities to our python
interpreter
3. Managing Migrations – Migrations allow us to generate a database schema based on model
code. In the end, migrations allow us to have a trace of the evolution of our database schema.
( as a version control system)
Makemigrations vs Migrate command
Migrate command creates an initial database based on Django’s default settings
NB: SQLite database is created first time we run either migrate or runserver. Runserver configures the
Database. Migrate command applies 18 default migrations – admin, auth, contenttypes and sessions
Makemigrations command – generates SQL commands for the defined models in all preinstalled apps in
our settings_apps setting. The migrations are stored in an auto-genbnerated folder, migrations.
4. Django admin interface: - Django has a powerful admin interface that provides visual display of
every aspect of a Django Project.
Createsuperuser
5. Database Viewer
Explanation of Fields and Features
unique_id: A UUID field serves as a unique identifier for each user profile. It's
automatically generated and cannot be edited by users.
user: A one-to-one relationship with the User model ensures that each user has a
corresponding profile. This relationship is defined using the OneToOneField field.
username: This field stores the username of the profile, and it's marked as unique to
ensure that no two profiles have the same username.
image: An ImageField is used for uploading a profile picture, with the images stored in
the profile_images/ directory. The field is optional.
bio: A text field that allows users to write a short biography or description of themselves.
This field is also optional.
skill: A character field where users can list their skills or areas of expertise. It is
optional and has a maximum length of 255 characters.
date_joined: A DateTimeField that records when the user profile was created. It
automatically sets the current date and time when the profile is first created.
last_login: This field is updated every time the user logs in, capturing the most recent
login time.
last_updated: This field is automatically updated whenever the profile is saved,
keeping track of the most recent time the profile was modified.
gender: An optional field that allows users to specify their gender. It uses Django's
TextChoices feature to provide predefined options.
github_profile: A URL field that allows users to link to their GitHub profile. This field
is also optional.