In Django, model refers to a python object/class which acts as source of information, represents structure of data and provides method to interact with the data. Generally a model maps to a single database table and attributes in the model map to the database table fields.
Create a django project and create an app in it:
django-admin startproject mytestproject
(navigate inside the project like cd mytestproject)
python manage.py startalp test1_app
In the file models.py :
class Articles(models.Model):
"to save data in the articles table"
title = models.CharField(max_length=150)
description = models.TextField()
created_by = models.CharField(max_length=150)
created_at = models.DateTimeField(default=timezone.now)
updated_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
class Meta:
db_table = 'articles'
Save the file and run:
python manage.py makemigrations
python manage.py migrate
ORM(Object-Relational Mapper) is an API acting as a bridge between the django models and the database. ORM provides the pythonic methods to interact to do CRUD operations on the database.
To use ORM, activate the shell:
python manage.py shell
Type:
from test_app.models import Articles
p1 = Articles(title='test title', description='testing desc notes', created_by='admin')
p1.save()
Articles.objects.all()
Articles.objects.values()
Articles.objects.filter(id=1).update(title='updated title')
Articles.objects.get(id=1)
Articles.objects.get(id=1).delete()
There are many other ORM methods.