Skip to main content

Python Django: Introduction to models and ORM

Python Django: Introduction to models and ORM

In the previous article we see django views, django template. In this artical we see the third component of MVT pattern, django models.

Here Object-Relational Mapping, ORM is an important concept. This allow for combination of of the OOP world of python and the relational database world of SQL. With ORM, Python classes, methods, and objects become the tools for interacting with SQL database.

In our demoApp, the next app is to add the database, django was designed for interacting with data, so it makes it easy to do so .

demoApp/models.py look like this

from django.db import models

  # Create your models here


now suppose we want to store the details of every user that comes to our website, so we need to create a model for user in demoApp/models.py. A model for user look like this

class Myuser(models.model):

first_name = models.CharField(max_length =
64)

last_name = models.CharField(max_length =
64)

age = models.IntegerField()

Inheriting models.model just establishes this class as django model.
Django has a number of built-in types of fields that map to different type of data in a SQL database, for instance. Eg:- IntergerField(), CharField()

Migrations:
Usually, tables are built up as the application grows, and the database will be modified. It would be tedious to change both the Django model code and run the SQL commands to modify the database.

Solution to this problem is Django migrations. Django automatically detects and changes to models.py and automatically generates the necessary SQL code to make the necessary changes.

For migration, run
python3 manage.py makemigrations

This will look through model files for any changes and generate a migration, which represents the necessary changes for the database. Running this command will create a filemigrations/0001_initial.py that contains everything that should happen to the database.
On runnning python3 manage.py migrate, the generated SQL command is executed and create user table in database that contains first_name, last_name and age as the column, and one additional column id which is automatically created by django.
The default database of django is SQLite, but you can always change this via settings.py.

Now back to views.py and import the Myuser and write the following code in views.py


In the temp views, we create several objects of Myuser and save. Obj.save is analogous to SQL COMMIT.

We can query of user using Myuser.objects.all() command and pass the it in context.
Django provide lots of default command for managing models like filtering object. In alluser template...


We can iterate over all user using template language looping, now run the server and go to page, its look like this. Right one is old page, we created in previous article and now we have a default page for all user.

Note that in here we are creating Myuser object in temp view, everytime url goes to temp views three new objects is created with name vikram, ankit and shanker.


This is the basic introduction, In the next article we use better approach to handle this.

Popular posts from this blog

Introduction to Java Security

Introduction to Java Security The Java security architecture includes a large set of application programming interfaces (APIs), tools, and implementations of commonly-used security algorithms, mechanisms, and protocols. The Java security APIs span a wide range of areas. Cryptographic and public key infrastructure (PKI) interfaces provide the underlying basis for developing secure applications. Interfaces for performing authentication and access control enable applications to guard against unauthorized access to protected resources. The JDK includes a number of providers that implement a core set of security services. It also allows for additional custom providers to be installed. This enables developers to extend the platform with new security mechanisms. The JDK is divided into modules. Modules that contain security APIs include the following:

Module Description java.base Defines the foundational APIs of Java SE;  contained packages include java.securityjavax.cryptojavax.net.ssl,  and…

SQL Injection

Overview A SQL injection attack consists of insertion or "injection" of a SQL query via the input data from the client to the application. A successful SQL injection exploit can read sensitive data from the database, modify database data (Insert/Update/Delete), execute administration operations on the database (such as shutdown the DBMS), recover the content of a given file present on the DBMS file system and in some cases issue commands to the operating system. SQL injection attacks are a type of injection attack, in which SQL commands are injected into data-plane input in order to effect the execution of predefined SQL commands. Threat ModelingSQL injection attacks allow attackers to spoof identity, tamper with existing data, cause repudiation issues such as voiding transactions or changing balances, allow the complete disclosure of all data on the system, destroy the data or make it otherwise unavailable, and become administrators of the database server.SQL Injection is ve…

Insertion Node in the Linkelist.

In this post, methods to insert a new node in linked list are discussed. A node can be added in three ways
1) At the front of the linked list
2) After a given node.
3) At the end of the linked list
public class Linkedlist { Node head; class Node{ int data; Node next; Node(int d){ data =d; next=null; } } // INSERT THE NODE AT THE BEGIN OF LINKEDLIST. public void insertAtfront(int new_data){ // Node temp = head; Node new_node = new Node(new_data); new_node.next = head; head = new_node; }  // INSERT THE NODE AT THE GIVEN POSITION IN LINKEDLIST.
public void insertAtGiven(Node prev_node,int new_data) { if(prev_node == null){ System.out.print("previous node can't be null"); return; } Node new_node = new Node(new_data); new_node.next = prev_node.next; prev_node.next = new_node; } // INSERT THE NODE  AT THE END OF THE LINKEDLIST.   public void insertAtEnd(int new_data){ Node new_node = new Node(new_data); new_node.nex…