SlideShare a Scribd company logo
Models in Django
Courtesy: djangoBook.com
Haris NP
haris@baabtra.com
www.facebook.com/haris.np
9
twitter.com/np_haris
in.linkedin.com/in/harisnp
MVC v/s MTV
• Model – Data access layer.
• View – Presentation Layer. What the user sees.
• Controller – Business Logic Layer. This layer
decides which view to use based on the user
input and which model to access.
MTV
• M stands for Model
• T stands for Template. This is presentation
layer.
• V stands for View. It is different from the MVC
architecture. It contains the business logic
layer. It access the model and calls the
Template as per the clicks.
Connecting to the database
• Settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # Add
'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'baabtra', # Or path to database file if using sqlite3. This is
the name of the database.
# The following settings are not used with sqlite3:
'USER': 'root',
'PASSWORD': 'itsbaabtra',
'HOST': 'localhost',
# Empty for localhost through
domain sockets or '127.0.0.1' for localhost through TCP.
'PORT': '3306',
# Set to empty string for default.
}
}
Screenshot of Database properties
from settings.py page (mysql)
Check the connectivity
• Go to the command prompt
• Traverse to the project folder Type :
python manage.py shell
• Type
– from django.db import connection
– cursor = connection.cursor()
If there is no error, then you have configured it
correctly.
Project v/s App in Django
• Project: Set of multiple apps with its
configuration.
• App: Set of Django functionality. Apps are
portable and reusable across multiple
projects.
• For starting an app, please use the following
command
python manage.py startapp nameoftheapp
• python manage.py startapp baabtramodel
INSTALLED_APP
• Models
– It is the description of the data in your database.
– It is written in python code.
– It is equivalent to CREATE TABLE. If the table doesn’t
exist, when the project is synched with the database that
you are creating, the tables are created. If you want to
migrate your application from MySQL to Postgres, you
don’t have to rewrite the SQL codes again.
– Since the SQL Codes are written in the python, version
control of database is easy. If there are modifications to
the existing database, it might create out of sync problems.
• Sample Model
class Category(models.Model):
category_code=models.CharField(max_length=10)
category_description=models.CharField(max_length=300)
def __unicode__(self):
return self.category_code
class Item(models.Model):
item_name=models.CharField(max_length=200)
item_code=models.CharField(max_length=10)
item_barcode=models.CharField(max_length=20)
item_description=models.CharField(max_length=300)
item_cost=models.FloatField(max_length=10)
item_retail_price=models.FloatField(max_length=10)
item_category_id=models.ForeignKey(Category)
def __unicode__(self):
return self.item_name
class Supplier(models.Model):
supplier_name=models.CharField(max_length=50)
supplier_code=models.CharField(max_length=10)
credit_period=models.CharField(max_length=50)
credit_limit=models.FloatField(max_length=10)
class Purchase_order(models.Model):
supplier_code=models.FloatField(max_length=15)
entry_date=models.DateField()
order_amount=models.FloatField(max_length=10)
net_amount=models.FloatField(max_length=15)
document_type=models.CharField(max_length=20)
class Purchase_items(models.Model):
order_id=models.FloatField(max_length=15)
item_id=models.FloatField(max_length=15)
item_quantity=models.FloatField(max_length=10)
item_rate=models.FloatField(max_length=10)
total_amount=models.FloatField(max_length=15)
• Now run the synchDB command using the
following command:
• Run python manage.py validate . This
command validates the model.
• python manage.py syncdb
• Basic data access
– Go to python manage.py shell
– Type the following

>>> from baabtramodel.models import Category
>>> obj_category = Category( category_code =
'Elect', category_description ='All kind of electronics
gadgets')
>>> obj_category .save()
Please note that the above code is used for inserting to
database table without foreign key reference
• Data is saved in the database. You can verify
by going to the database as shown below.
• Adding two more category objects
>>> obj_category2 = Category( category_code =
'Cod2', category_description ='category desc2')
>>> obj_category3 = Category( category_code =
'cod3', category_description ='category desc3')
>>> obj_category2.save()
>>> obj_category3.save()
• List the objects
>>> category_list = Category.objects.all()
>>> category_list
It lists all the objects along with the code name.
It
• Reason: Copy pasting the model snippet
below
class Category(models.Model):
category_code=models.CharField(max_length=10)
category_description=models.CharField(max_length=300)
def __unicode__(self):
return self.category_code

• The __unicode__(self) is playing the trick. A
__unicode__() method tells Python how to
display the “unicode” representation of an
object. As we have given category_code, we
will get Elect, Cod2 and Cod3 when the
objects are listed.
[<Category: Elect>, <Category:
Cod2>, <Category: cod3>]
• You can add multiple strings to a unicode.
def __unicode__(self):
return u'%s %s' %
(self.category_code, self.category_description)

Then it will print both category code and description as
shown below.
• Updating data in the database.
>>> obj_category2 = Category( category_code =
'Cod2', category_description ='category desc2')
>>> obj_category2 .save()
>>> obj_category2 .id
7 # Depending upon your entry in the table it
can defer.
• From the database

>>> obj_category2.category_code= 'code‘
>>> obj_category2.save()

Again from the database

Please note that cod2 has been changed to ‘code’
Selecting data from the database
• Select * from baabtramodel_category can be
achieved by the following code
• Category.objects.all() #where Category is the
class name in the model.
• Filtering data
>>> Category.objects.filter(category_code='Elect')

>>>Category.objects.filter(category_code='Elect‘, category_descr
iption=‘All kind of electronics gadgets’)

Now change the criteria as
>>>Category.objects.filter(category_code='Elect', category_descr
iption='All kind of electronics gadget') # doesn’t exist any row in
the table which satisfy the criteria
• SQL “like”
>>>Category.objects.filter(category_code__cont
ains ='cod')

Please note that it is case sensitive. Data in the
database
Retrieving single objects
>>> Category.objects.get(id=7)
>>> Category.objects.get(category_code =‘code’)
A query that returns more than two or no records causes an exception
Error:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:Python27libsite-packagesdjangodbmodelsmanager.py", line 143, in
get
return self.get_query_set().get(*args, **kwargs)
File "C:Python27libsite-packagesdjangodbmodelsquery.py", line 407, in g
et
(self.model._meta.object_name, num))
MultipleObjectsReturned: get() returned more than one Category -- it returned 2!
Order by and chaining look ups
For descending
>>>Category.objects.filter(category_code__cont
ains ='cod').order_by("category_description")
For ascending
>>>Category.objects.filter(category_code__cont
ains ='cod').order_by(“category_description”)
Slicing of Data
>>>Category.objects.order_by('category_code')[
0]
Returns only one row.
>>>Category.objects.order_by('category_code')[
0:2]
Updating multiple rows
>>> Category.objects.all().update
(category_code='CodeU')
SQL View:
Inserting data in Django to tables with foreign key
reference.
>>> from baabtramodel.models import Item
>>> obj_item = Item( item_name=
'pen', item_code='p', item_barcode
='bc001', item_description ='Used for
writing', item_cost = 10, item_retail_price =15
, item_category_id =1)
• Error
• Traceback (most recent call last):
– File “<console>”, line 1, in <module>
– File “C:Python27…. base.py”, line 403, in __init__
• setattr(self, field.name, rel_obj)
– File “C:Python27….related.py”, line 405, in __set__
• Self.field_name, self.field.rel.to._meta.object_name)

– ValueError: Cannot assign “1”: “Item.item_category_id”
must be a “Category” instance.
Fix
• Create an instance of the Category.
>>> from baabtramodel.models import Category
>>> category_id = Category.objects.get(id=1)
>>> from baabtramodel.models import Item
>>> obj_item = Item( item_name=
'pen', item_code='p', item_barcode
='bc001', item_description ='Used for writing', item_cost
= 10, item_retail_price =15 , item_category_id
=category_id )
Please note that category_id is an instance and not the
variable inside the object.
• From a sample application
views.py
• Please note that we are passing categoryid
directly here. It must be changed to an
instance.
Updated views.py
• Please note that Id is an instance of the class
Category
• The author takes corporate trainings in
Android, Java, JQuery, JavaScript and Python. In case
if your organization needs training, please connect
through www.massbaab.com/baabtra.
• Baabtra provides both online and offline trainings for
candidates who want to learn latest programming
technologies , frameworks like
codeigniter, django, android, iphone app
development
• Baabtra also provides basic training in
SQL, .NET, PHP, Java and Python who wants to start
their career in IT.
Session 2 django material for training at baabtra models

More Related Content

What's hot

Python Metaclasses
Python MetaclassesPython Metaclasses
Python Metaclasses
Nikunj Parekh
 
Tutorial: Develop an App with the Odoo Framework
Tutorial: Develop an App with the Odoo FrameworkTutorial: Develop an App with the Odoo Framework
Tutorial: Develop an App with the Odoo Framework
Odoo
 
SQL200.3 Module 3
SQL200.3 Module 3SQL200.3 Module 3
SQL200.3 Module 3
Dan D'Urso
 
Practical Object Oriented Models In Sql
Practical Object Oriented Models In SqlPractical Object Oriented Models In Sql
Practical Object Oriented Models In Sql
Karwin Software Solutions LLC
 
SQL Server 2008 R2 System Views Map
SQL Server 2008 R2 System Views MapSQL Server 2008 R2 System Views Map
SQL Server 2008 R2 System Views MapPaulo Freitas
 
Sql server 2008_system_views_poster
Sql server 2008_system_views_posterSql server 2008_system_views_poster
Sql server 2008_system_views_poster
Ngọa Long
 
Form demoinplaywithmysql
Form demoinplaywithmysqlForm demoinplaywithmysql
Form demoinplaywithmysql
Knoldus Inc.
 
Odoo - Business intelligence: Develop cube views for your own objects
Odoo - Business intelligence: Develop cube views for your own objectsOdoo - Business intelligence: Develop cube views for your own objects
Odoo - Business intelligence: Develop cube views for your own objects
Odoo
 
PyCon SG x Jublia - Building a simple-to-use Database Management tool
PyCon SG x Jublia - Building a simple-to-use Database Management toolPyCon SG x Jublia - Building a simple-to-use Database Management tool
PyCon SG x Jublia - Building a simple-to-use Database Management tool
Crea Very
 
R Language
R LanguageR Language
R Language
ShwetDadhaniya1
 
Wicket KT part 2
Wicket KT part 2Wicket KT part 2
Wicket KT part 2
stuq
 
Learning sql from w3schools
Learning sql from w3schoolsLearning sql from w3schools
Learning sql from w3schools
farhan516
 
Django Admin (Python meeutp)
Django Admin (Python meeutp)Django Admin (Python meeutp)
Django Admin (Python meeutp)
Ines Jelovac
 
AVB202 Intermediate Microsoft Access VBA
AVB202 Intermediate Microsoft Access VBAAVB202 Intermediate Microsoft Access VBA
AVB202 Intermediate Microsoft Access VBA
Dan D'Urso
 
Start your app the better way with Styled System
Start your app the better way with Styled SystemStart your app the better way with Styled System
Start your app the better way with Styled System
Hsin-Hao Tang
 
SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2
SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2
SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2
Dan D'Urso
 
WooCommerce CRUD and Data Store by Akeda Bagus
WooCommerce CRUD and Data Store by Akeda BagusWooCommerce CRUD and Data Store by Akeda Bagus
WooCommerce CRUD and Data Store by Akeda Bagus
WordCamp Indonesia
 
OQL querying and indexes with Apache Geode (incubating)
OQL querying and indexes with Apache Geode (incubating)OQL querying and indexes with Apache Geode (incubating)
OQL querying and indexes with Apache Geode (incubating)
Jason Huynh
 
ADO.NET Entity Framework by Jose A. Blakeley and Michael Pizzo
ADO.NET Entity Framework by Jose A. Blakeley and Michael PizzoADO.NET Entity Framework by Jose A. Blakeley and Michael Pizzo
ADO.NET Entity Framework by Jose A. Blakeley and Michael Pizzo
Hasnain Iqbal
 

What's hot (20)

Python Metaclasses
Python MetaclassesPython Metaclasses
Python Metaclasses
 
Tutorial: Develop an App with the Odoo Framework
Tutorial: Develop an App with the Odoo FrameworkTutorial: Develop an App with the Odoo Framework
Tutorial: Develop an App with the Odoo Framework
 
SQL200.3 Module 3
SQL200.3 Module 3SQL200.3 Module 3
SQL200.3 Module 3
 
Practical Object Oriented Models In Sql
Practical Object Oriented Models In SqlPractical Object Oriented Models In Sql
Practical Object Oriented Models In Sql
 
SQL Server 2008 R2 System Views Map
SQL Server 2008 R2 System Views MapSQL Server 2008 R2 System Views Map
SQL Server 2008 R2 System Views Map
 
Sql server 2008_system_views_poster
Sql server 2008_system_views_posterSql server 2008_system_views_poster
Sql server 2008_system_views_poster
 
Form demoinplaywithmysql
Form demoinplaywithmysqlForm demoinplaywithmysql
Form demoinplaywithmysql
 
Odoo - Business intelligence: Develop cube views for your own objects
Odoo - Business intelligence: Develop cube views for your own objectsOdoo - Business intelligence: Develop cube views for your own objects
Odoo - Business intelligence: Develop cube views for your own objects
 
PyCon SG x Jublia - Building a simple-to-use Database Management tool
PyCon SG x Jublia - Building a simple-to-use Database Management toolPyCon SG x Jublia - Building a simple-to-use Database Management tool
PyCon SG x Jublia - Building a simple-to-use Database Management tool
 
R Language
R LanguageR Language
R Language
 
Wicket KT part 2
Wicket KT part 2Wicket KT part 2
Wicket KT part 2
 
Learning sql from w3schools
Learning sql from w3schoolsLearning sql from w3schools
Learning sql from w3schools
 
Django Admin (Python meeutp)
Django Admin (Python meeutp)Django Admin (Python meeutp)
Django Admin (Python meeutp)
 
Table views
Table viewsTable views
Table views
 
AVB202 Intermediate Microsoft Access VBA
AVB202 Intermediate Microsoft Access VBAAVB202 Intermediate Microsoft Access VBA
AVB202 Intermediate Microsoft Access VBA
 
Start your app the better way with Styled System
Start your app the better way with Styled SystemStart your app the better way with Styled System
Start your app the better way with Styled System
 
SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2
SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2
SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2
 
WooCommerce CRUD and Data Store by Akeda Bagus
WooCommerce CRUD and Data Store by Akeda BagusWooCommerce CRUD and Data Store by Akeda Bagus
WooCommerce CRUD and Data Store by Akeda Bagus
 
OQL querying and indexes with Apache Geode (incubating)
OQL querying and indexes with Apache Geode (incubating)OQL querying and indexes with Apache Geode (incubating)
OQL querying and indexes with Apache Geode (incubating)
 
ADO.NET Entity Framework by Jose A. Blakeley and Michael Pizzo
ADO.NET Entity Framework by Jose A. Blakeley and Michael PizzoADO.NET Entity Framework by Jose A. Blakeley and Michael Pizzo
ADO.NET Entity Framework by Jose A. Blakeley and Michael Pizzo
 

Similar to Session 2 django material for training at baabtra models

The Django Book - Chapter 5: Models
The Django Book - Chapter 5: ModelsThe Django Book - Chapter 5: Models
The Django Book - Chapter 5: Models
Sharon Chen
 
Data Migrations in the App Engine Datastore
Data Migrations in the App Engine DatastoreData Migrations in the App Engine Datastore
Data Migrations in the App Engine Datastore
Ryan Morlok
 
171_74_216_Module_5-Non_relational_database_-mongodb.pptx
171_74_216_Module_5-Non_relational_database_-mongodb.pptx171_74_216_Module_5-Non_relational_database_-mongodb.pptx
171_74_216_Module_5-Non_relational_database_-mongodb.pptx
sukrithlal008
 
MVC Design Pattern in JavaScript by ADMEC Multimedia Institute
MVC Design Pattern in JavaScript by ADMEC Multimedia InstituteMVC Design Pattern in JavaScript by ADMEC Multimedia Institute
MVC Design Pattern in JavaScript by ADMEC Multimedia Institute
Ravi Bhadauria
 
PerlApp2Postgresql (2)
PerlApp2Postgresql (2)PerlApp2Postgresql (2)
PerlApp2Postgresql (2)Jerome Eteve
 
Mongo db basics
Mongo db basicsMongo db basics
Mongo db basics
Dhaval Mistry
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
Omnia Helmi
 
Learn D3.js in 90 minutes
Learn D3.js in 90 minutesLearn D3.js in 90 minutes
Learn D3.js in 90 minutes
Jos Dirksen
 
Data herding
Data herdingData herding
Data herding
unbracketed
 
Creating Single Page Web App using Backbone JS
Creating Single Page Web App using Backbone JSCreating Single Page Web App using Backbone JS
Creating Single Page Web App using Backbone JS
Akshay Mathur
 
Optimization in django orm
Optimization in django ormOptimization in django orm
Optimization in django orm
Denys Levchenko
 
Django workshop : let's make a blog
Django workshop : let's make a blogDjango workshop : let's make a blog
Django workshop : let's make a blog
Pierre Sudron
 
Tutorial - Learn SQL with Live Online Database
Tutorial - Learn SQL with Live Online DatabaseTutorial - Learn SQL with Live Online Database
Tutorial - Learn SQL with Live Online Database
DBrow Adm
 

Similar to Session 2 django material for training at baabtra models (20)

The Django Book - Chapter 5: Models
The Django Book - Chapter 5: ModelsThe Django Book - Chapter 5: Models
The Django Book - Chapter 5: Models
 
Jsp project module
Jsp project moduleJsp project module
Jsp project module
 
Data Migrations in the App Engine Datastore
Data Migrations in the App Engine DatastoreData Migrations in the App Engine Datastore
Data Migrations in the App Engine Datastore
 
Mvc acchitecture
Mvc acchitectureMvc acchitecture
Mvc acchitecture
 
171_74_216_Module_5-Non_relational_database_-mongodb.pptx
171_74_216_Module_5-Non_relational_database_-mongodb.pptx171_74_216_Module_5-Non_relational_database_-mongodb.pptx
171_74_216_Module_5-Non_relational_database_-mongodb.pptx
 
MVC Design Pattern in JavaScript by ADMEC Multimedia Institute
MVC Design Pattern in JavaScript by ADMEC Multimedia InstituteMVC Design Pattern in JavaScript by ADMEC Multimedia Institute
MVC Design Pattern in JavaScript by ADMEC Multimedia Institute
 
PerlApp2Postgresql (2)
PerlApp2Postgresql (2)PerlApp2Postgresql (2)
PerlApp2Postgresql (2)
 
Mongo db basics
Mongo db basicsMongo db basics
Mongo db basics
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
 
CAD Report
CAD ReportCAD Report
CAD Report
 
Django Pro ORM
Django Pro ORMDjango Pro ORM
Django Pro ORM
 
Django
DjangoDjango
Django
 
CodeIgniter & MVC
CodeIgniter & MVCCodeIgniter & MVC
CodeIgniter & MVC
 
Learn D3.js in 90 minutes
Learn D3.js in 90 minutesLearn D3.js in 90 minutes
Learn D3.js in 90 minutes
 
Data herding
Data herdingData herding
Data herding
 
Data herding
Data herdingData herding
Data herding
 
Creating Single Page Web App using Backbone JS
Creating Single Page Web App using Backbone JSCreating Single Page Web App using Backbone JS
Creating Single Page Web App using Backbone JS
 
Optimization in django orm
Optimization in django ormOptimization in django orm
Optimization in django orm
 
Django workshop : let's make a blog
Django workshop : let's make a blogDjango workshop : let's make a blog
Django workshop : let's make a blog
 
Tutorial - Learn SQL with Live Online Database
Tutorial - Learn SQL with Live Online DatabaseTutorial - Learn SQL with Live Online Database
Tutorial - Learn SQL with Live Online Database
 

More from baabtra.com - No. 1 supplier of quality freshers

Acquiring new skills what you should know
Acquiring new skills   what you should knowAcquiring new skills   what you should know
Acquiring new skills what you should know
baabtra.com - No. 1 supplier of quality freshers
 
Baabtra.com programming at school
Baabtra.com programming at schoolBaabtra.com programming at school
Baabtra.com programming at school
baabtra.com - No. 1 supplier of quality freshers
 
99LMS for Enterprises - LMS that you will love
99LMS for Enterprises - LMS that you will love 99LMS for Enterprises - LMS that you will love
99LMS for Enterprises - LMS that you will love
baabtra.com - No. 1 supplier of quality freshers
 
Php database connectivity
Php database connectivityPhp database connectivity
Chapter 6 database normalisation
Chapter 6  database normalisationChapter 6  database normalisation
Chapter 6 database normalisation
baabtra.com - No. 1 supplier of quality freshers
 
Chapter 5 transactions and dcl statements
Chapter 5  transactions and dcl statementsChapter 5  transactions and dcl statements
Chapter 5 transactions and dcl statements
baabtra.com - No. 1 supplier of quality freshers
 
Chapter 4 functions, views, indexing
Chapter 4  functions, views, indexingChapter 4  functions, views, indexing
Chapter 4 functions, views, indexing
baabtra.com - No. 1 supplier of quality freshers
 
Chapter 3 stored procedures
Chapter 3 stored proceduresChapter 3 stored procedures
Chapter 2 grouping,scalar and aggergate functions,joins inner join,outer join
Chapter 2  grouping,scalar and aggergate functions,joins   inner join,outer joinChapter 2  grouping,scalar and aggergate functions,joins   inner join,outer join
Chapter 2 grouping,scalar and aggergate functions,joins inner join,outer join
baabtra.com - No. 1 supplier of quality freshers
 
Chapter 1 introduction to sql server
Chapter 1 introduction to sql serverChapter 1 introduction to sql server
Chapter 1 introduction to sql server
baabtra.com - No. 1 supplier of quality freshers
 
Microsoft holo lens
Microsoft holo lensMicrosoft holo lens
Blue brain
Blue brainBlue brain
5g
5g5g
Aptitude skills baabtra
Aptitude skills baabtraAptitude skills baabtra

More from baabtra.com - No. 1 supplier of quality freshers (20)

Agile methodology and scrum development
Agile methodology and scrum developmentAgile methodology and scrum development
Agile methodology and scrum development
 
Best coding practices
Best coding practicesBest coding practices
Best coding practices
 
Core java - baabtra
Core java - baabtraCore java - baabtra
Core java - baabtra
 
Acquiring new skills what you should know
Acquiring new skills   what you should knowAcquiring new skills   what you should know
Acquiring new skills what you should know
 
Baabtra.com programming at school
Baabtra.com programming at schoolBaabtra.com programming at school
Baabtra.com programming at school
 
99LMS for Enterprises - LMS that you will love
99LMS for Enterprises - LMS that you will love 99LMS for Enterprises - LMS that you will love
99LMS for Enterprises - LMS that you will love
 
Php sessions & cookies
Php sessions & cookiesPhp sessions & cookies
Php sessions & cookies
 
Php database connectivity
Php database connectivityPhp database connectivity
Php database connectivity
 
Chapter 6 database normalisation
Chapter 6  database normalisationChapter 6  database normalisation
Chapter 6 database normalisation
 
Chapter 5 transactions and dcl statements
Chapter 5  transactions and dcl statementsChapter 5  transactions and dcl statements
Chapter 5 transactions and dcl statements
 
Chapter 4 functions, views, indexing
Chapter 4  functions, views, indexingChapter 4  functions, views, indexing
Chapter 4 functions, views, indexing
 
Chapter 3 stored procedures
Chapter 3 stored proceduresChapter 3 stored procedures
Chapter 3 stored procedures
 
Chapter 2 grouping,scalar and aggergate functions,joins inner join,outer join
Chapter 2  grouping,scalar and aggergate functions,joins   inner join,outer joinChapter 2  grouping,scalar and aggergate functions,joins   inner join,outer join
Chapter 2 grouping,scalar and aggergate functions,joins inner join,outer join
 
Chapter 1 introduction to sql server
Chapter 1 introduction to sql serverChapter 1 introduction to sql server
Chapter 1 introduction to sql server
 
Chapter 1 introduction to sql server
Chapter 1 introduction to sql serverChapter 1 introduction to sql server
Chapter 1 introduction to sql server
 
Microsoft holo lens
Microsoft holo lensMicrosoft holo lens
Microsoft holo lens
 
Blue brain
Blue brainBlue brain
Blue brain
 
5g
5g5g
5g
 
Aptitude skills baabtra
Aptitude skills baabtraAptitude skills baabtra
Aptitude skills baabtra
 
Gd baabtra
Gd baabtraGd baabtra
Gd baabtra
 

Recently uploaded

Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
g2nightmarescribd
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 

Recently uploaded (20)

Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 

Session 2 django material for training at baabtra models

  • 1.
  • 2. Models in Django Courtesy: djangoBook.com Haris NP haris@baabtra.com www.facebook.com/haris.np 9 twitter.com/np_haris in.linkedin.com/in/harisnp
  • 3. MVC v/s MTV • Model – Data access layer. • View – Presentation Layer. What the user sees. • Controller – Business Logic Layer. This layer decides which view to use based on the user input and which model to access.
  • 4. MTV • M stands for Model • T stands for Template. This is presentation layer. • V stands for View. It is different from the MVC architecture. It contains the business logic layer. It access the model and calls the Template as per the clicks.
  • 5. Connecting to the database • Settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'baabtra', # Or path to database file if using sqlite3. This is the name of the database. # The following settings are not used with sqlite3: 'USER': 'root', 'PASSWORD': 'itsbaabtra', 'HOST': 'localhost', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP. 'PORT': '3306', # Set to empty string for default. } }
  • 6. Screenshot of Database properties from settings.py page (mysql)
  • 7. Check the connectivity • Go to the command prompt • Traverse to the project folder Type : python manage.py shell
  • 8. • Type – from django.db import connection – cursor = connection.cursor() If there is no error, then you have configured it correctly.
  • 9. Project v/s App in Django • Project: Set of multiple apps with its configuration. • App: Set of Django functionality. Apps are portable and reusable across multiple projects. • For starting an app, please use the following command python manage.py startapp nameoftheapp
  • 10. • python manage.py startapp baabtramodel
  • 12. • Models – It is the description of the data in your database. – It is written in python code. – It is equivalent to CREATE TABLE. If the table doesn’t exist, when the project is synched with the database that you are creating, the tables are created. If you want to migrate your application from MySQL to Postgres, you don’t have to rewrite the SQL codes again. – Since the SQL Codes are written in the python, version control of database is easy. If there are modifications to the existing database, it might create out of sync problems.
  • 13. • Sample Model class Category(models.Model): category_code=models.CharField(max_length=10) category_description=models.CharField(max_length=300) def __unicode__(self): return self.category_code class Item(models.Model): item_name=models.CharField(max_length=200) item_code=models.CharField(max_length=10) item_barcode=models.CharField(max_length=20) item_description=models.CharField(max_length=300) item_cost=models.FloatField(max_length=10) item_retail_price=models.FloatField(max_length=10) item_category_id=models.ForeignKey(Category) def __unicode__(self): return self.item_name class Supplier(models.Model): supplier_name=models.CharField(max_length=50) supplier_code=models.CharField(max_length=10) credit_period=models.CharField(max_length=50) credit_limit=models.FloatField(max_length=10) class Purchase_order(models.Model): supplier_code=models.FloatField(max_length=15) entry_date=models.DateField() order_amount=models.FloatField(max_length=10) net_amount=models.FloatField(max_length=15) document_type=models.CharField(max_length=20) class Purchase_items(models.Model): order_id=models.FloatField(max_length=15) item_id=models.FloatField(max_length=15) item_quantity=models.FloatField(max_length=10) item_rate=models.FloatField(max_length=10) total_amount=models.FloatField(max_length=15)
  • 14.
  • 15. • Now run the synchDB command using the following command: • Run python manage.py validate . This command validates the model. • python manage.py syncdb
  • 16.
  • 17. • Basic data access – Go to python manage.py shell – Type the following >>> from baabtramodel.models import Category >>> obj_category = Category( category_code = 'Elect', category_description ='All kind of electronics gadgets') >>> obj_category .save() Please note that the above code is used for inserting to database table without foreign key reference
  • 18. • Data is saved in the database. You can verify by going to the database as shown below.
  • 19.
  • 20. • Adding two more category objects >>> obj_category2 = Category( category_code = 'Cod2', category_description ='category desc2') >>> obj_category3 = Category( category_code = 'cod3', category_description ='category desc3') >>> obj_category2.save() >>> obj_category3.save()
  • 21. • List the objects >>> category_list = Category.objects.all() >>> category_list It lists all the objects along with the code name. It
  • 22. • Reason: Copy pasting the model snippet below class Category(models.Model): category_code=models.CharField(max_length=10) category_description=models.CharField(max_length=300) def __unicode__(self): return self.category_code • The __unicode__(self) is playing the trick. A __unicode__() method tells Python how to display the “unicode” representation of an object. As we have given category_code, we will get Elect, Cod2 and Cod3 when the objects are listed. [<Category: Elect>, <Category: Cod2>, <Category: cod3>]
  • 23. • You can add multiple strings to a unicode. def __unicode__(self): return u'%s %s' % (self.category_code, self.category_description) Then it will print both category code and description as shown below.
  • 24. • Updating data in the database. >>> obj_category2 = Category( category_code = 'Cod2', category_description ='category desc2') >>> obj_category2 .save() >>> obj_category2 .id 7 # Depending upon your entry in the table it can defer.
  • 25. • From the database >>> obj_category2.category_code= 'code‘ >>> obj_category2.save() Again from the database Please note that cod2 has been changed to ‘code’
  • 26. Selecting data from the database • Select * from baabtramodel_category can be achieved by the following code • Category.objects.all() #where Category is the class name in the model.
  • 27. • Filtering data >>> Category.objects.filter(category_code='Elect') >>>Category.objects.filter(category_code='Elect‘, category_descr iption=‘All kind of electronics gadgets’) Now change the criteria as >>>Category.objects.filter(category_code='Elect', category_descr iption='All kind of electronics gadget') # doesn’t exist any row in the table which satisfy the criteria
  • 28. • SQL “like” >>>Category.objects.filter(category_code__cont ains ='cod') Please note that it is case sensitive. Data in the database
  • 29. Retrieving single objects >>> Category.objects.get(id=7) >>> Category.objects.get(category_code =‘code’) A query that returns more than two or no records causes an exception Error: Traceback (most recent call last): File "<console>", line 1, in <module> File "C:Python27libsite-packagesdjangodbmodelsmanager.py", line 143, in get return self.get_query_set().get(*args, **kwargs) File "C:Python27libsite-packagesdjangodbmodelsquery.py", line 407, in g et (self.model._meta.object_name, num)) MultipleObjectsReturned: get() returned more than one Category -- it returned 2!
  • 30. Order by and chaining look ups For descending >>>Category.objects.filter(category_code__cont ains ='cod').order_by("category_description") For ascending >>>Category.objects.filter(category_code__cont ains ='cod').order_by(“category_description”)
  • 31. Slicing of Data >>>Category.objects.order_by('category_code')[ 0] Returns only one row. >>>Category.objects.order_by('category_code')[ 0:2]
  • 32. Updating multiple rows >>> Category.objects.all().update (category_code='CodeU') SQL View:
  • 33. Inserting data in Django to tables with foreign key reference. >>> from baabtramodel.models import Item >>> obj_item = Item( item_name= 'pen', item_code='p', item_barcode ='bc001', item_description ='Used for writing', item_cost = 10, item_retail_price =15 , item_category_id =1)
  • 34. • Error • Traceback (most recent call last): – File “<console>”, line 1, in <module> – File “C:Python27…. base.py”, line 403, in __init__ • setattr(self, field.name, rel_obj) – File “C:Python27….related.py”, line 405, in __set__ • Self.field_name, self.field.rel.to._meta.object_name) – ValueError: Cannot assign “1”: “Item.item_category_id” must be a “Category” instance.
  • 35. Fix • Create an instance of the Category. >>> from baabtramodel.models import Category >>> category_id = Category.objects.get(id=1) >>> from baabtramodel.models import Item >>> obj_item = Item( item_name= 'pen', item_code='p', item_barcode ='bc001', item_description ='Used for writing', item_cost = 10, item_retail_price =15 , item_category_id =category_id ) Please note that category_id is an instance and not the variable inside the object.
  • 36.
  • 37. • From a sample application
  • 38. views.py • Please note that we are passing categoryid directly here. It must be changed to an instance.
  • 39. Updated views.py • Please note that Id is an instance of the class Category
  • 40. • The author takes corporate trainings in Android, Java, JQuery, JavaScript and Python. In case if your organization needs training, please connect through www.massbaab.com/baabtra. • Baabtra provides both online and offline trainings for candidates who want to learn latest programming technologies , frameworks like codeigniter, django, android, iphone app development • Baabtra also provides basic training in SQL, .NET, PHP, Java and Python who wants to start their career in IT.