Note_Tech

All technological notes.


Project maintained by simonangel-fong Hosted on GitHub Pages — Theme by mattgraham

Django - Model

Back


Model


Migration

Command Description
makemigrations create a migration py file for the tabled schema of a model.
migrate create table according to the schema defined in the migration file.
sqlmigrate show a raw SQL query of the applied migration.
showmigrations lists out all the migrations and their status.

Example: Create model and migrate

Create model class: models.py

from django.db import models

class Employee(models.Model):
    first_name = models.CharField(max_length=32)
    last_name = models.CharField(max_length=32)
    email = models.EmailField()

Register Model: settings.py

INSTALLED_APPS = [
  #...
  'app_name',
  #...
]

Create Migration Files: makemigrations

# create migration files for all apps
$ py manage.py makemigrations

# create migrations files for a specific app
$ py manage.py makemigrations app_label1 app_label2 ...

Update Database: migrate

$ py manage.py migrate [app_label] [migration_name]

List Migrations Files(Opetional): showmigrations

# show migrations for all apps
$ py manage.py showmigrations

# show migrations for specific apps
$ py manage.py showmigrations [app_label]

# return:
# EmpApp
#  [X] 0001_initial

Prit SQL Code(Optional): sqlmigrate

$ py manage.py sqlmigrate app_label migration_name
# app_label: the name of current application
# migration_name: the name of migration file


# example:
$ py manage.py sqlmigrate EmpApp 0001
# return:
# BEGIN;
# --
# -- Create model Employee
# --
# CREATE TABLE "EmpApp_employee" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "first_name" varchar(32) NOT NULL, "last_name" varchar(32) NOT NULL, "email" varchar(254) NOT NULL);
# COMMIT;

Model Class

Exception

Exception Description
Model.DoesNotExist when an expected object is not found
Model.MultipleObjectsReturned when multiple objects are found

Attributes

Attributes Description
Model.objects the default name of the Manager

Instance method

Method Description
Model(**kwargs) instantiatie a model without db
Method Description
refresh_from_db() reload a model’s values from the database
get_deferred_fields() return the attribute names of all fields
Method Description
clean_fields() validate all fields on model
clean() custom model validation
validate_unique() validates uniqueness constraints
validate_constraints() validates all constraints
full_clean() call the above methods
Method Description
save() insert / udpate an object back to the database
delete() deletes the object in the database
Method Description
__str__() display a model instance
__eq__() compare primary key value
get_absolute_url() return a HTTP string to refer to the object
get_field_name_display() returns the “human-readable” value of the choice field

TOP