session 2 django material for training at baabtra models
Upload: baabtracom-mentoring-partner-first-programming-school-in-india
Post on 23-Jan-2015
829 views
DESCRIPTION
This is for candidates who wants to learn models in django. Python version used is 2.7 and the database used is MySQL. Operating system is Windows 8.TRANSCRIPT
![Page 1: Session 2 django material for training at baabtra models](https://reader037.vdocuments.us/reader037/viewer/2022110115/54c208c14a795989198b4574/html5/thumbnails/1.jpg)
![Page 2: Session 2 django material for training at baabtra models](https://reader037.vdocuments.us/reader037/viewer/2022110115/54c208c14a795989198b4574/html5/thumbnails/2.jpg)
Models in DjangoCourtesy: djangoBook.com
Haris [email protected]/haris.np9twitter.com/np_harisin.linkedin.com/in/harisnp
![Page 3: Session 2 django material for training at baabtra models](https://reader037.vdocuments.us/reader037/viewer/2022110115/54c208c14a795989198b4574/html5/thumbnails/3.jpg)
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.
![Page 4: Session 2 django material for training at baabtra models](https://reader037.vdocuments.us/reader037/viewer/2022110115/54c208c14a795989198b4574/html5/thumbnails/4.jpg)
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.
![Page 5: Session 2 django material for training at baabtra models](https://reader037.vdocuments.us/reader037/viewer/2022110115/54c208c14a795989198b4574/html5/thumbnails/5.jpg)
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. }}
![Page 6: Session 2 django material for training at baabtra models](https://reader037.vdocuments.us/reader037/viewer/2022110115/54c208c14a795989198b4574/html5/thumbnails/6.jpg)
Screenshot of Database properties from settings.py page (mysql)
![Page 7: Session 2 django material for training at baabtra models](https://reader037.vdocuments.us/reader037/viewer/2022110115/54c208c14a795989198b4574/html5/thumbnails/7.jpg)
Check the connectivity
• Go to the command prompt • Traverse to the project folder Type :
python manage.py shell
![Page 8: Session 2 django material for training at baabtra models](https://reader037.vdocuments.us/reader037/viewer/2022110115/54c208c14a795989198b4574/html5/thumbnails/8.jpg)
• Type – from django.db import connection– cursor = connection.cursor()If there is no error, then you have configured it correctly.
![Page 9: Session 2 django material for training at baabtra models](https://reader037.vdocuments.us/reader037/viewer/2022110115/54c208c14a795989198b4574/html5/thumbnails/9.jpg)
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
![Page 10: Session 2 django material for training at baabtra models](https://reader037.vdocuments.us/reader037/viewer/2022110115/54c208c14a795989198b4574/html5/thumbnails/10.jpg)
• python manage.py startapp baabtramodel
![Page 11: Session 2 django material for training at baabtra models](https://reader037.vdocuments.us/reader037/viewer/2022110115/54c208c14a795989198b4574/html5/thumbnails/11.jpg)
INSTALLED_APP
![Page 12: Session 2 django material for training at baabtra models](https://reader037.vdocuments.us/reader037/viewer/2022110115/54c208c14a795989198b4574/html5/thumbnails/12.jpg)
• 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.
![Page 13: Session 2 django material for training at baabtra models](https://reader037.vdocuments.us/reader037/viewer/2022110115/54c208c14a795989198b4574/html5/thumbnails/13.jpg)
• Sample Modelclass Category(models.Model): category_code=models.CharField(max_length=10) category_description=models.CharField(max_length=300) def __unicode__(self): return self.category_codeclass 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)
![Page 14: Session 2 django material for training at baabtra models](https://reader037.vdocuments.us/reader037/viewer/2022110115/54c208c14a795989198b4574/html5/thumbnails/14.jpg)
![Page 15: Session 2 django material for training at baabtra models](https://reader037.vdocuments.us/reader037/viewer/2022110115/54c208c14a795989198b4574/html5/thumbnails/15.jpg)
• Now run the synchDB command using the following command:
• Run python manage.py validate . This command validates the model.
• python manage.py syncdb
![Page 16: Session 2 django material for training at baabtra models](https://reader037.vdocuments.us/reader037/viewer/2022110115/54c208c14a795989198b4574/html5/thumbnails/16.jpg)
![Page 17: Session 2 django material for training at baabtra models](https://reader037.vdocuments.us/reader037/viewer/2022110115/54c208c14a795989198b4574/html5/thumbnails/17.jpg)
• 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
![Page 18: Session 2 django material for training at baabtra models](https://reader037.vdocuments.us/reader037/viewer/2022110115/54c208c14a795989198b4574/html5/thumbnails/18.jpg)
• Data is saved in the database. You can verify by going to the database as shown below.
![Page 19: Session 2 django material for training at baabtra models](https://reader037.vdocuments.us/reader037/viewer/2022110115/54c208c14a795989198b4574/html5/thumbnails/19.jpg)
![Page 20: Session 2 django material for training at baabtra models](https://reader037.vdocuments.us/reader037/viewer/2022110115/54c208c14a795989198b4574/html5/thumbnails/20.jpg)
• 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()
![Page 21: Session 2 django material for training at baabtra models](https://reader037.vdocuments.us/reader037/viewer/2022110115/54c208c14a795989198b4574/html5/thumbnails/21.jpg)
• List the objects>>> category_list = Category.objects.all()>>> category_listIt lists all the objects along with the code name. It
![Page 22: Session 2 django material for training at baabtra models](https://reader037.vdocuments.us/reader037/viewer/2022110115/54c208c14a795989198b4574/html5/thumbnails/22.jpg)
• 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>]
![Page 23: Session 2 django material for training at baabtra models](https://reader037.vdocuments.us/reader037/viewer/2022110115/54c208c14a795989198b4574/html5/thumbnails/23.jpg)
• 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.
![Page 24: Session 2 django material for training at baabtra models](https://reader037.vdocuments.us/reader037/viewer/2022110115/54c208c14a795989198b4574/html5/thumbnails/24.jpg)
• Updating data in the database. >>> obj_category2 = Category( category_code = 'Cod2', category_description ='category desc2')>>> obj_category2 .save()>>> obj_category2 .id7 # Depending upon your entry in the table it can defer.
![Page 25: Session 2 django material for training at baabtra models](https://reader037.vdocuments.us/reader037/viewer/2022110115/54c208c14a795989198b4574/html5/thumbnails/25.jpg)
• From the database
>>> obj_category2.category_code= 'code‘>>> obj_category2.save()
Again from the database
Please note that cod2 has been changed to ‘code’
![Page 26: Session 2 django material for training at baabtra models](https://reader037.vdocuments.us/reader037/viewer/2022110115/54c208c14a795989198b4574/html5/thumbnails/26.jpg)
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.
![Page 27: Session 2 django material for training at baabtra models](https://reader037.vdocuments.us/reader037/viewer/2022110115/54c208c14a795989198b4574/html5/thumbnails/27.jpg)
• Filtering data>>> Category.objects.filter(category_code='Elect')
>>>Category.objects.filter(category_code='Elect‘, category_description=‘All kind of electronics gadgets’)
Now change the criteria as >>>Category.objects.filter(category_code='Elect', category_description='All kind of electronics gadget') # doesn’t exist any row in the table which satisfy the criteria
![Page 28: Session 2 django material for training at baabtra models](https://reader037.vdocuments.us/reader037/viewer/2022110115/54c208c14a795989198b4574/html5/thumbnails/28.jpg)
• SQL “like”>>>Category.objects.filter(category_code__contains ='cod')
Please note that it is case sensitive. Data in the database
![Page 29: Session 2 django material for training at baabtra models](https://reader037.vdocuments.us/reader037/viewer/2022110115/54c208c14a795989198b4574/html5/thumbnails/29.jpg)
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 exceptionError: Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Python27\lib\site-packages\django\db\models\manager.py", line 143, in get return self.get_query_set().get(*args, **kwargs) File "C:\Python27\lib\site-packages\django\db\models\query.py", line 407, in get (self.model._meta.object_name, num))MultipleObjectsReturned: get() returned more than one Category -- it returned 2!
![Page 30: Session 2 django material for training at baabtra models](https://reader037.vdocuments.us/reader037/viewer/2022110115/54c208c14a795989198b4574/html5/thumbnails/30.jpg)
Order by and chaining look ups
For descending>>>Category.objects.filter(category_code__contains ='cod').order_by("category_description") For ascending>>>Category.objects.filter(category_code__contains ='cod').order_by(“category_description”)
![Page 31: Session 2 django material for training at baabtra models](https://reader037.vdocuments.us/reader037/viewer/2022110115/54c208c14a795989198b4574/html5/thumbnails/31.jpg)
Slicing of Data
>>>Category.objects.order_by('category_code')[0]Returns only one row. >>>Category.objects.order_by('category_code')[0:2]
![Page 32: Session 2 django material for training at baabtra models](https://reader037.vdocuments.us/reader037/viewer/2022110115/54c208c14a795989198b4574/html5/thumbnails/32.jpg)
Updating multiple rows
>>> Category.objects.all().update (category_code='CodeU')SQL View:
![Page 33: Session 2 django material for training at baabtra models](https://reader037.vdocuments.us/reader037/viewer/2022110115/54c208c14a795989198b4574/html5/thumbnails/33.jpg)
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)
![Page 34: Session 2 django material for training at baabtra models](https://reader037.vdocuments.us/reader037/viewer/2022110115/54c208c14a795989198b4574/html5/thumbnails/34.jpg)
• 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.
![Page 35: Session 2 django material for training at baabtra models](https://reader037.vdocuments.us/reader037/viewer/2022110115/54c208c14a795989198b4574/html5/thumbnails/35.jpg)
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.
![Page 36: Session 2 django material for training at baabtra models](https://reader037.vdocuments.us/reader037/viewer/2022110115/54c208c14a795989198b4574/html5/thumbnails/36.jpg)
![Page 37: Session 2 django material for training at baabtra models](https://reader037.vdocuments.us/reader037/viewer/2022110115/54c208c14a795989198b4574/html5/thumbnails/37.jpg)
• From a sample application
![Page 38: Session 2 django material for training at baabtra models](https://reader037.vdocuments.us/reader037/viewer/2022110115/54c208c14a795989198b4574/html5/thumbnails/38.jpg)
views.py
• Please note that we are passing categoryid directly here. It must be changed to an instance.
![Page 39: Session 2 django material for training at baabtra models](https://reader037.vdocuments.us/reader037/viewer/2022110115/54c208c14a795989198b4574/html5/thumbnails/39.jpg)
Updated views.py
• Please note that Id is an instance of the class Category
![Page 40: Session 2 django material for training at baabtra models](https://reader037.vdocuments.us/reader037/viewer/2022110115/54c208c14a795989198b4574/html5/thumbnails/40.jpg)
• 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.
![Page 41: Session 2 django material for training at baabtra models](https://reader037.vdocuments.us/reader037/viewer/2022110115/54c208c14a795989198b4574/html5/thumbnails/41.jpg)