The following is a handy command that lets us explore the ORM and create new records
$ python manage.py shell
QuerySet
>>> from courses.models import Course
>>> Course.objects.all()
[]
This looks like a list, but it’s not!
It’s actually an empty QuerySet.
>>> type(Course.objects.all())
<class 'django.db.models.query.QuerySet'>
Creating the Instance
Method 1: Assigning Attributes
Let’s create an instance
>>> c = Course()
>>> c.title = "Python Basics"
>>> c.description = "Learn the basics of Python"
>>> c.save()
>>> Course.objects.all()
[<Course: Couese object>]
Method 2: Object Instantiation
>>> Course(title="Python Collections", description="Learn about list, dict, and tuple").save()
>>> Course.objects.all()
[<Course: Couese object>, <Course: Couese object>]
Method 3: Object Instantiation
This is the best way to do it!
>>> Course.objects.create(title="Object-Oriented Python", description="Learn about Python's classes")
<Course: Couese object>
create
Returns an object after instance creation.
Enhance Query Presentation
from django.db import models
class Course(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=255)
description = models.TextField()
def __str__(self):
return self.title
>>> Course.objects.all()
[<Course: Python Basics>, <Course: Python Collections>, <Course: Object-Oriented Python>]