About me

Monday, May 14, 2018

Python django chap 4 (Working With API for CRUD operations)

                                    

Friends this is the continuation from its previous post so i kindly recommend you to read that post i have made this very simple even a complete beginner can learn it and if you are beginner in python then you need to learn python i have made that blog also for that click this link

                 

 

                  WORKING WITH API for CRUD operations


  First you go into the interactive Python shell and play around with the free API Django gives you. To invoke the Python shell, use this command:

$ python manage.py shell
We’re using this instead of simply typing “python”, because manage.py sets the DJANGO_SETTINGS_MODULE environment variable, which gives Django the Python import path to your pysite/settings.py file.
           
Let's create a "crudops" view to see how we can do CRUD operations(CREATE,READ,UPDATE AND DELETE) on models. Our myproj/views.py will then look like −
from myapp.models import Dreamreal
from django.http import HttpResponse

def crudops(request):
   #Creating an entry
   
   mytable = Mytable(
      website = "www.nads.com", mail = "nads@sani.com", 
      name = "nadssani", phonenumber = "8075467438"
   )
   
   mytable.save()
   
   #Read ALL entries
   objects = Mytable.objects.all()
   res ='Printing all Mytable entries in the DB : <br>'
   
   for elt in objects:
      res += elt.name+"<br>"
   
   #Read a specific entry:
   nadssani = Mytable.objects.get(name = "nadssani")
   res += 'Printing One entry <br>'
   res += nadssani.name
   
   #Delete an entry
   res += '<br> Deleting an entry <br>'
   nadssani.delete()
   
   #Update
   mytable = Mytable(
      website = "www.nads.com", mail = "nads@sani.com", 
      name = "nadssani", phonenumber = "8075467438"
   )
   
   mytable.save()
   res += 'Updating entry<br>'
   
   mytable = Dreamreal.objects.get(name = 'nadssani')
   mytable.name = 'rawther'
   mytable.save()
   
   return HttpResponse(res)
 
 
 
 
Now i will explain each of the process here To represent database-table data in Python objects, Django uses an intuitive system: A model class represents a database table, and an instance of that class represents a particular record in the database table. To create an object, instantiate it using keyword arguments to the model class, then call save() to save it to the database.
After to read all the entries we have made we first select all then we print each of them in second line and then now we need to select the specific entry from the table for that we select with the get (name = nadssani) statement . and to delete the value we simply delete using the "nadssani.delete()".
and at last update the value also is done.


The save method have no return value

To create and save an object in a single step use create() method

Other Queryset Methods

we can also retrieve specific objects with filter() method if you need to select only a subset of the complete set of objects.to refine we use the initial query set  like that we obtained earlier
"filter(**kwargs)" method Returns a new QuerySet containing objects that match the given lookup parameters and "exclude(**kwargs)" method returns a new QuerySet containing objects that doesn't matches the given lookup parameters
Here we are giving a different example from earlier to get a lookup of  QuerySet of blog entries from the year 2018  use filter on the here with the Entry class objects

Entry.objects.filter(pub_date_year = 2018)
With the default class it is same as the 

Entry.objects.all().filter(pub_date__year=2018)
Most of the time we use methods like all(),get(),filter()and exclude() when you need to lookup objects from the database to get all the queryset methods click here

Linking Models

The other part to learn is the Linking of Models The 3 ways are many to one ,many to many , one to one
Many to one
       
To define a many-to-one relationship, use django .db. models .ForeignKey You use it just like any other Field type: by including it as a class attribute of your model. This ForeignKey () method needs a positional arguments which is the class to which it is related for example if software has a relation with a software company like company makes different softwares but the company is one softwares are many like for example :

from django.db import models
 class Company(models.Model):
     # ...
     pass
 class Software(models.Model):
     company = models.ForeignKey(Company, on_delete=models.CASCADE)
      # ...

Many to many relationship

To define many to many relationship , use ManyToManyField. use it just like any other Field type: by including it as a class attribute of your model. ManyToManyField requires a positional argument: the class to which the model is related.for example here if a building has many floors that means every floors can be on multiple buildings and each buildings will have multiple floors :

from from django.db import models
   class Floors(models.Model):
      # ...
      pass
  class Buildings(models.Model):
       # ...
      floors = models.ManyToManyField(Floors)

One to one relationship

To define a one-to-one relationship, use OneToOneField. You use it just like any other Field type: by including it as a class attribute of your model.OneToOneField requires a positional argument .the class to which the model is related for example if you were building a database of “places”, you would build pretty standard stuff such as address, phone number, etc. in the database. Then, if you wanted to build a database of restaurants on top of the places, instead of repeating yourself and replicating those fields in the Restaurant model, you could make Restaurant have a OneToOneField to Place (because a restaurant “is a” place; in fact, to handle this you’d typically use inheritance, which involves an implicit one-to-one relation). 


THANKS FOR VIEWING MY BLOG HOPE YOU LIKE THE POST IF ANY DOUBTS FEEL FREE TO ASK AND IF YOU WANT TO GET THE LATEST CHAPTERS AND UPDATES ON THIS BLOG PLEASE FOLLOW WITH YOUR E-MAIL ID AND DON'T FORGET TO SHARE AND COMMENT THIS POST

No comments:

Post a Comment