0% found this document useful (0 votes)
33 views

L07-Django Models & Databases

Uploaded by

123 456
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views

L07-Django Models & Databases

Uploaded by

123 456
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

CSC309 – LECTURE 07

DJANGO MODELS & DATABASES


Khai Truong
Database
Web applications often use a database to organize, store and retrieve
data
Many choices for primary database
● Relational: MySQL, PostgreSQL
● Non-relational: MongoDB, Cassandra

Great to have choices, but…


Too many choices = danger of needing to
write lots of code to access and manage
each different database
Announcements
Extension to A1 & P1
● Each gets pushed back 2 days
● Deadlines for subsequent assignments not affected

Autotester
● Ignore color, do font size that makes sense for you

Booking system
● Fixed…
Django’s default database backend
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3’,
'NAME': BASE_DIR / 'db.sqlite3’,
}
}

Lightweight database that stores Great for development: no setup or


everything in a file installation required
Follows standard SQL syntax For production, a more scalable
database is required
Django object relational mapper (ORM)
Django includes an object-oriented layer
● Separates application from database implementation
● Supports various relational database backends (such as SQLite,
PostgreSQL, and MySQL)
ORM does not require the use of SQL queries
● Method calls and attribute accesses are translated to queries
● Query results are encapsulated in objects and their attributes

See list of built-in support


● https://docs.djangoproject.com/en/4.2/ref/settings/#databases
ORM advantages vs. disadvantages
Advantages
● Simplicity: no need to learn SQL or other database languages
● Consistency: everything is in the same language
● Flexibility: can switch database backend easily
● Security: runs secure queries that can prevent attacks like SQL
injection
● Seamless conversion from in-memory types to storage types, and
vice versa
Disadvantages
● Additional layer of abstraction reduces overall performance
● Hiding implementation detail may result in poorly designed
database schema
Django models
Represents, stores, and manages application data
Typically implemented as one or more tables in database
The ORM layer enables defining models with classes

Django has a set of predefined models for convenience


● User: Django’s default model for authentication and authorization
● Permission: what a user can or cannot do
● Session: stores data on server-side about current site visitor
Setting up database tables
The database is empty initially, with no tables

To add/update tables: python manage.py migrate


The ORM layer will create or update database tables to match the
model definitions
Add app to project’s settings.py
Django shell
python manage.py shell

Provides interactive Python shell within Django environment


Enables testing models without running a web server
Working with ORM
Every model (Python class) has an objects class attribute (e.g.,
User.objects)

objects is used to perform the equivalence to database queries, such as


SELECT, INSERT, etc. statements

Most of objects’ methods creates a QuerySet


Some common methods
all() : Retrieves all objects of that type
● e.g., User.objects.all() retrieves all User objects
filter() : Returns a list of objects based on one or more field lookups
● Syntax: filter(fieldname__lookup=value, …)
● e.g., User.objects.filter(last_name="Smith", age__gt=19)

get() : Get just one object based on exact match


● e.g., dan=User.objects.get(username='dan1995’) Can raise an
ObjectDoesNotExist or a
MultipleObjectsReturned
exception
Some common methods
create() : Creates a new object
● e.g., SomeModel.objects.create(variable=”value”)
● Some fields are optional and do not need to be specified during
create
● Creating a user requires create_user()
delete() : Performs a delete on a single object or an entire QuerySet

● e.g., user.delete() or User.objects.all.delete()


order_by() : Sort the objects in QuerySet by specific field(s)
● e.g., User.objects.order_by('first_name', 'last_name’)
Updating data
Update a single instance
dan = User.objects.get(first_name='Daniel’)
dan.first_name = 'Dan’
dan.save()

Update everything in a QuerySet


User.objects.filter(is_active=True).update(is_active=False)

Beware of stale states: Attributes are locally cached values


● Refresh: dan.refresh_from_db()
Common methods & lookups
A lot of methods and field lookups!
● Methods: exclude(), annotate(), distinct(), etc.
● Lookups: in, iexact (case-insensitive match), isnull, etc.

https://docs.djangoproject.com/en/4.2/ref/models/querysets/
QuerySets
QuerySets can be chained
● Results must satisfy all conditions (same effect as the AND operator)
● Useful for applying multiple filters and sort orders

Number of results can be limited by using Python slice operator


● Useful for pagination, to split results into multiple pages
● E.g., to return first 10 results: User.objects.all()[:10]
Lazy evaluation
Queries are not run until field of object is accessed to improve the
efficiency of queries
For example:
users = User.objects.all()
users2 = users.exclude(is_active=False)
users3 = users2.filter(username__contains='test’)
user = users3.get()
user.get_full_name()
Only one query is run
Django security model
Authentication
Verifies the identity of a user or service
Typically done through verification of correct username and password
● Other methods include API key, session token, certificate, etc.

Two-factor authentication: provides additional layer of protection by


asking additional information
● E.g., one-time passcode sent to email or phone

Authorization
Determines a user’s access right
Checks user’s privilege level (group) and permissions
User authentication in Django
User:Derived class of AbstractUser
Contains predefined fields: username, firstname, lastname, email, etc.
Passwords are hashed before they are stored
Passwords are also salted before hashing
● Prevents a rainbow table attack
● Salt is a random value that is added to the password
Authentication
Clients should tell the server who they are
Can use Authorization header in HTTP
Several authentication methods available
● Password auth
● Session auth
● Token auth
Basic
Password authentication
Sends username and password for every request
● No concept of login and logout

User information is unencrypted and encoded in base64


● Insecure without HTTPS
Session authentication
Client only sends username and password at login
If successful, server creates and stores a session id
● Session id is mapped to the specific user

Session id is returned in the response


● Browser saves it in cookies
● Session data is saved on server, and not saved in cookie!

Browser sends the same session id for subsequent requests


Incognito mode: browser does
not send session id*
Token authentication
Token is signed by server to avoid attacks
Can be used to identify the client and their permissions (analogous to
using your driver’s license to go into a bar/club)
Much faster than session because no database query is needed
JSON web token (JWT): industry standard method for securely
representing claims (which can contain your information, including
identity and/or permissions)
Session vs token based authentication

https://sherryhsu.medium.com/session-vs-token-based-authentication-11a6c5ac45e4
Django session authentication
Checks that username/password combination is correct
user =authenticate(username='john',password='secret’)
Attaches user to the current session
login(request, user)
Django does the session id lookup internally
● User object is attached to the request object (request.user)
● User type is AnonymousUser if current visitor is not authenticated

Removes session data


logout(request)
http://localhost:8000/admin
Admin panel
Instead of running raw queries or python code through python
manage.py shell, admin panel is a convenient way to see/change
database records
The admin panel is installed by default
● See the global urls.py
Requires an activeuser with is_superuser and is_staff field set to True
● Can be created manually through the shell
● Or created via the admin panel itself
● Or via command: python manage.py createsuperuser
Much of this lecture was taken from content previously created by Jack Sun & Kianoosh Abbasi

Reproduction and/or sharing of course materials is prohibited. Course materials include lecture slides, course notes,
assignments, data and documents provided by the instructors. Course materials created by the instructors of this course
are their intellectual properties. They may not be shared, posted, rehosted, sold, or otherwise distributed and/or
modified without expressed permission from the authors. All such reproduction or dissemination is an infringement of
copyright and is prohibited. All rights are reserved by the instructors.

Thank you & questions?

You might also like