Difference between revisions of "Python-Django/C2/Django-Shell-and-Django-Database-Query/English"
Pravin1389 (Talk | contribs) (Created page with ".") |
Nancyvarkey (Talk | contribs) |
||
(One intermediate revision by one other user not shown) | |||
Line 1: | Line 1: | ||
− | . | + | '''Django/C2/Django_Shell_and_Django_Database_Query/English''' |
+ | |||
+ | '''Title of script: '''Django Shell and Django Database Query | ||
+ | |||
+ | '''Keywords: '''Video tutorial, Django Shell, Django Database Query | ||
+ | |||
+ | |||
+ | |||
+ | {| border = “1” | ||
+ | |- | ||
+ | || '''Visual cue''' | ||
+ | || '''Narration''' | ||
+ | |- | ||
+ | || Slide: Django Shell and Django Database Query | ||
+ | || Hello and welcome to the spoken tutorial on''' “Django Shell and Django Database Query”.''' | ||
+ | |- | ||
+ | || Slide: Learning Objectives | ||
+ | || In this tutorial, we will learn to: | ||
+ | |||
+ | * Use the '''Django shell '''and | ||
+ | * Create a '''Django Query''' | ||
+ | |- | ||
+ | || Slide: System Requirements | ||
+ | || To practice this tutorial, I am using | ||
+ | |||
+ | * '''Ubuntu Linux 16.04 OS''' | ||
+ | * '''Python 3.5 ''' | ||
+ | * '''Python 3.4-venv '''or higher | ||
+ | * '''gedit Text Editor''' | ||
+ | |||
+ | However, you can use any other '''text editor '''of your choice. | ||
+ | |- | ||
+ | || Slide: Prerequisites | ||
+ | || To follow this tutorial, you need to know | ||
+ | |||
+ | * How to create '''models''' in '''Django''' | ||
+ | * If not, then please go through the prerequisite tutorials in this series. | ||
+ | |- | ||
+ | || Slide: What is the Django Shell ? | ||
+ | || | ||
+ | * The '''Django shell''' is a '''Python shell''' configured for our '''Django project.''' | ||
+ | * We can execute our '''project code''' in this '''shell.''' | ||
+ | * We can manipulate our '''app models '''in this '''shell.''' | ||
+ | |||
+ | |- | ||
+ | || Open a Terminal window | ||
+ | Press CTRl+ALT+T simultaneously | ||
+ | || Let us open the '''terminal '''by pressing '''Ctrl''', '''Alt''' and '''T '''keys simultaneously on your keyboard. | ||
+ | |||
+ | |- | ||
+ | || [Terminal] | ||
+ | |||
+ | cd '''my-django '''[Enter] | ||
+ | || Now using '''cd command''', we will go to the '''folder my hyphen django '''which we had created earlier. | ||
+ | |||
+ | |- | ||
+ | || [Terminal] | ||
+ | Type source myapp_env/bin/activate [Enter] | ||
+ | || Activate the '''virtual environment myapp underscore env''' | ||
+ | |||
+ | |- | ||
+ | | [Terminal] | ||
+ | cd '''mysite''' and Press Enter | ||
+ | || Now let us go to the '''folder mysite.''' | ||
+ | |- | ||
+ | || | ||
+ | || Here onwards, please remember to press the '''Enter''' key after typing each '''command'''. | ||
+ | |- | ||
+ | || [Terminal] | ||
+ | |||
+ | Type python manage.py shell [Enter] | ||
+ | || Let us now type the '''command-''' | ||
+ | |||
+ | '''python manage dot py <space> shell''' | ||
+ | |- | ||
+ | || [Terminal] | ||
+ | |||
+ | Highlight (point to the shell) | ||
+ | |||
+ | '''(InteractiveConsole)''' | ||
+ | |||
+ | '''>>> ''' | ||
+ | || We are now in the '''Interactive console.''' | ||
+ | |- | ||
+ | || Slide: Interactive console | ||
+ | || | ||
+ | |||
+ | * The '''Interactive console''' provides a perfect '''complement''' to the '''Python environment''' | ||
+ | * It allows interactive '''editing, running''' and '''debugging''' of our '''Python project''' | ||
+ | |||
+ | |- | ||
+ | || Switch to Terminal | ||
+ | || Switch back to '''terminal'''. | ||
+ | |- | ||
+ | || [Terminal]Type: | ||
+ | |||
+ | from blog.models import Blog [Enter] | ||
+ | |||
+ | from django.utils import timezone [Enter] | ||
+ | |||
+ | blog = Blog(name='My Second Blog', created_on=timezone.now()) [Enter] | ||
+ | |||
+ | blog.save() [Enter] | ||
+ | || Let us run a '''Django query '''to add a new '''Blog.''' | ||
+ | |||
+ | Type the '''commands '''one by one as shown here. | ||
+ | |||
+ | |- | ||
+ | || [Terminal] | ||
+ | |||
+ | Highlight | ||
+ | |||
+ | '''from blog.models import Blog''' | ||
+ | || To add a new '''Blog''', we need to''' import Blog''' from our '''models.''' | ||
+ | |- | ||
+ | || [Terminal] | ||
+ | |||
+ | Highlight | ||
+ | |||
+ | '''blog = Blog(name='My Second Blog', created_on=timezone.now())''' | ||
+ | || Here we have created a''' Blog instance.''' | ||
+ | |||
+ | |- | ||
+ | || [Terminal] | ||
+ | |||
+ | Highlight | ||
+ | |||
+ | blog = Blog'''(name='My Second Blog', created_on=timezone.now())''' | ||
+ | || Also, we have added values to its '''fields - name''' and '''creation date.''' | ||
+ | |- | ||
+ | || [Terminal] | ||
+ | |||
+ | Highlight | ||
+ | |||
+ | '''created_on=timezone.now()''' | ||
+ | || '''created_on attribute '''is not needed while creating a''' new blog object.''' | ||
+ | |||
+ | |||
+ | This is because we have already defined a default value for '''created_on attribute '''in '''models. ''' | ||
+ | |||
+ | |||
+ | For learning purpose, we have shown how to assign a value to '''created_on attribute.'''. | ||
+ | |- | ||
+ | || [Terminal] | ||
+ | |||
+ | Highlight | ||
+ | |||
+ | '''from django.utils import timezone ''' | ||
+ | || To get the creation date, we import '''timezone''' from '''django dot utils module.''' | ||
+ | |- | ||
+ | || [Terminal] | ||
+ | |||
+ | Highlight | ||
+ | |||
+ | '''blog.save()''' | ||
+ | || Then, save the '''object '''that we have created. | ||
+ | |||
+ | So, '''Django '''writes this information to the '''database table Blog.''' | ||
+ | |- | ||
+ | || [Terminal] Type: | ||
+ | |||
+ | blog.id [Enter] | ||
+ | || Let's now access the '''model '''field values through '''Python attributes.''' | ||
+ | |||
+ | To do so, type '''blog dot id''' | ||
+ | |- | ||
+ | || [Terminal] | ||
+ | |||
+ | In Output, Highlight '''2''' | ||
+ | || Here, the output shows '''two.''' | ||
+ | |||
+ | It is the '''id''' of the '''Blog object''' that we have created now. | ||
+ | |- | ||
+ | || [Terminal] | ||
+ | |||
+ | Type blog.name [Enter] | ||
+ | || To display the name of the '''Blog object''', type '''blog dot name''' | ||
+ | |- | ||
+ | || [Terminal] | ||
+ | |||
+ | In Output, Highlight ''''My Second Blog'''' | ||
+ | || Our '''Blog object '''name ''''My Second Blog' '''is being displayed. | ||
+ | |- | ||
+ | || [Terminal] | ||
+ | |||
+ | Type blog.created_on [Enter] | ||
+ | || To see the '''date time values''' of our '''Blog object''', type | ||
+ | |||
+ | '''blog dot created underscore on''' | ||
+ | |- | ||
+ | || [Terminal] | ||
+ | |||
+ | In Output, Highlight '''datetime.datetime(....)''' | ||
+ | || Here, it shows the date and time when the '''Blog '''was created. | ||
+ | |- | ||
+ | || [Terminal] | ||
+ | |||
+ | Type: | ||
+ | |||
+ | blog.name = 'This is a blog from shell' [Enter] | ||
+ | || Let us now change the name of our '''Blog object'''. | ||
+ | |||
+ | |||
+ | To do so, type''' blog dot name equal to '''within''' single quotes '''the''' '''new name for the '''blog.''' | ||
+ | |||
+ | |||
+ | I have typed-''' “This is a blog from shell”.''' | ||
+ | |- | ||
+ | || [Terminal] Highlight | ||
+ | |||
+ | '''blog.name = 'This is a Blog from shell'''' | ||
+ | || This will change the name in the output as '''This is a Blog from shell.''' | ||
+ | |- | ||
+ | || [Terminal] Type blog.save() [Enter] | ||
+ | || Save the '''blog'''. | ||
+ | |- | ||
+ | || [Terminal] Type blog.name [Enter] | ||
+ | || Then recall the '''blog dot name command '''and execute it. | ||
+ | |- | ||
+ | || [Terminal] In Output, Highlight | ||
+ | |||
+ | ''''This is a Blog from shell'''' | ||
+ | || We can see the name as ''''This is a Blog from shell'''' | ||
+ | |||
+ | |||
+ | So far, we have created and made changes on a '''Blog object '''via '''shell.''' | ||
+ | |- | ||
+ | || [Terminal] | ||
+ | |||
+ | |||
+ | Type: | ||
+ | |||
+ | Blog.objects.all() [Enter] | ||
+ | || To get all '''Blog objects''' using '''Query, '''type | ||
+ | |||
+ | |||
+ | '''Blog dot objects dot all''' '''opening and closing parentheses''' | ||
+ | |- | ||
+ | || [Terminal] In Output, Highlight | ||
+ | |||
+ | '''<QuerySet [<Blog: Blog object (1)>, <Blog: Blog object (2)>]> ''' | ||
+ | || In the output, we can see the '''Queryset''' with a '''list''' of '''Blog objects.''' | ||
+ | |||
+ | |||
+ | '''Blog object''' in the output is not a good representation for the '''object.''' | ||
+ | |- | ||
+ | || [Terminal] | ||
+ | |||
+ | |||
+ | Press Ctrl + D keys | ||
+ | || Let us fix this in the '''models.py '''file. | ||
+ | |||
+ | |||
+ | Quit from the''' shell''' by pressing '''Ctrl''' and '''D''' keys together. | ||
+ | |- | ||
+ | || [Terminal] | ||
+ | |||
+ | |||
+ | Type gedit blog/models.py & [Enter] | ||
+ | || Then open the '''models.py''' file in any '''text editor'''. | ||
+ | |- | ||
+ | || [blog/models.py] | ||
+ | |||
+ | |||
+ | from django.db import models | ||
+ | |||
+ | <nowiki># Create your models here.</nowiki> | ||
+ | |||
+ | class Blog(models.Model): | ||
+ | |||
+ | name = models.CharField(max_length=120) | ||
+ | |||
+ | created_on = models.DateTimeField(auto_now_add=True)''' | ||
+ | |||
+ | def __str__(self): | ||
+ | |||
+ | return self.name''' | ||
+ | |||
+ | class Article(models.Model): | ||
+ | |||
+ | blog = models.ForeignKey(Blog, on_delete=models.CASCADE) | ||
+ | |||
+ | created_on = models.DateTimeField(auto_now_add=True) | ||
+ | |||
+ | title = models.CharField(max_length=120) | ||
+ | |||
+ | body = models.TextField() | ||
+ | |||
+ | draft = models.BooleanField(default=False)''' | ||
+ | |||
+ | def __str__(self): | ||
+ | |||
+ | return self.title''' | ||
+ | || We are now in the '''models.py '''file. | ||
+ | |||
+ | |||
+ | Add a '''string method''' below the '''class Blog '''and '''Article '''as shown here. | ||
+ | |||
+ | |||
+ | For ease of practice, this code is provided in the Code Files link of this tutorial. | ||
+ | |||
+ | |||
+ | Please download, unzip and use it. | ||
+ | |- | ||
+ | || [models.py] | ||
+ | |||
+ | Highlight | ||
+ | |||
+ | '''def __str__(self):''' | ||
+ | || We define a '''String method''' inside the '''class''' to get '''string representation''' of the '''object.''' | ||
+ | |- | ||
+ | || [models.py] | ||
+ | |||
+ | Highlight | ||
+ | |||
+ | '''return self.name''' | ||
+ | || Here, the '''String method '''returns the '''name''' of our '''Blog model.''' | ||
+ | |||
+ | |- | ||
+ | || [models.py] | ||
+ | |||
+ | Highlight | ||
+ | |||
+ | '''return self.title''' | ||
+ | || Similarly, for the '''Article model, '''let’s return the '''title.''' | ||
+ | |||
+ | |- | ||
+ | || [models.py] | ||
+ | |||
+ | Highlight the complete code | ||
+ | || We have added the '''string method.''' | ||
+ | |||
+ | So now when we retrieve a '''Blog object,''' | ||
+ | |||
+ | we will see its name. | ||
+ | |||
+ | Lets understand this better. | ||
+ | |- | ||
+ | || Press Ctrl+S | ||
+ | || Save the file. | ||
+ | |- | ||
+ | || Switch to Terminal | ||
+ | || Then switch to the '''terminal.''' | ||
+ | |- | ||
+ | || [Terminal] Type: | ||
+ | |||
+ | python manage.py shell [Enter] | ||
+ | || And activate the '''Shell.''' | ||
+ | |- | ||
+ | || [Terminal]In Shell, Type: | ||
+ | |||
+ | '''from blog.models import Blog [Enter] ''' | ||
+ | || Import the '''blog models.''' | ||
+ | |- | ||
+ | || [Terminal]In Shell, Type:''' ''' | ||
+ | |||
+ | '''Blog.objects.all() [Enter]''' | ||
+ | || And run the '''Django Query''' as we did before. | ||
+ | |- | ||
+ | || [Terminal] In Output, Highlight | ||
+ | |||
+ | '''<QuerySet[...<Blog: This is a blog from shell!...']>''' | ||
+ | || It returns all the '''instances''' of the '''Blog model''' along with its '''name.''' | ||
+ | |- | ||
+ | || [Terminal] | ||
+ | |||
+ | |||
+ | |||
+ | |||
+ | Press Ctrl + D keys | ||
+ | || Now, let's add a '''custom method''' to the '''Blog model''' in '''models.py''' file. | ||
+ | |||
+ | |||
+ | Quit from the '''shell.''' | ||
+ | |- | ||
+ | || Switch to models.py file | ||
+ | || Switch to the '''models.py''' file. | ||
+ | |- | ||
+ | || [models.py] | ||
+ | |||
+ | from django.db import models | ||
+ | |||
+ | from django.utils import timezone | ||
+ | |||
+ | <nowiki># Create your models here.</nowiki> | ||
+ | |||
+ | class Blog(models.Model): | ||
+ | |||
+ | name = models.CharField(max_length=120) | ||
+ | |||
+ | created_on = models.DateTimeField(auto_now_add=True) | ||
+ | |||
+ | def __str__(self): | ||
+ | |||
+ | return self.name | ||
+ | |||
+ | ''' def was_created_recently(self): | ||
+ | |||
+ | return self.created_on >= timezone.now() - timezone.timedelta(days=1)''' | ||
+ | |||
+ | || Now, modify the '''class Blog '''as shown here. | ||
+ | |||
+ | |||
+ | Also import the '''timezone module''' from '''django.utils''' | ||
+ | |- | ||
+ | || [models.py] Highlight '''timezone.now()''' | ||
+ | || '''timezone.now()''' returns a '''date time''' that represents the current time. | ||
+ | |- | ||
+ | || [models.py] Highlight '''timezone.timedelta''' | ||
+ | || '''timedelta''' expresses the duration difference between | ||
+ | * two dates, | ||
+ | * two time inputs or | ||
+ | * two date-time stamps. | ||
+ | |||
+ | |- | ||
+ | || [models.py] Highlight | ||
+ | |||
+ | '''from django.utils import timezone''' | ||
+ | || To store '''timezone '''information, we '''import package timezone '''from''' django dot utils module.''' | ||
+ | |- | ||
+ | || [models.py] | ||
+ | |||
+ | Highlight | ||
+ | |||
+ | '''def was_created_recently(self): return self.created_on >= timezone.now() - timezone.timedelta(days=1)''' | ||
+ | || The '''"method was created recently”''' checks whether the '''Blog''' is created more recent than a day. | ||
+ | |||
+ | |||
+ | This is done by subtracting 1 day from the current time. | ||
+ | |||
+ | |||
+ | Then comparing, if the saved time is greater than that. | ||
+ | |- | ||
+ | || [models.py] Highlight the complete code | ||
+ | || So we have added the '''method '''to '''Blog.''' | ||
+ | |- | ||
+ | || Press Ctrl+S | ||
+ | || Save the file. | ||
+ | |- | ||
+ | || Switch to Terminal | ||
+ | || Switch to the '''terminal'''. | ||
+ | |- | ||
+ | || [Terminal] Type: | ||
+ | |||
+ | python manage.py shell [Enter] | ||
+ | || And activate the '''shell.''' | ||
+ | |- | ||
+ | || [Terminal] In Shell, Type: | ||
+ | |||
+ | from blog.models import Blog [Enter] | ||
+ | || '''Import''' the '''blog models.''' | ||
+ | |- | ||
+ | || blog = Blog.objects.get(name=”This is a Blog from shell!”) [Enter] | ||
+ | |||
+ | |||
+ | blog1 = Blog.objects.get(name=”My First Blog”) [Enter] | ||
+ | || The '''variable ‘blog’ '''has been lost as we quit from the '''shell''' to modify our '''model.''' | ||
+ | |||
+ | |||
+ | Let us retrieve a '''blog object '''by using '''get() method''' as shown here. | ||
+ | |- | ||
+ | || [Terminal] Type: | ||
+ | |||
+ | blog.was_created_recently() [Enter] | ||
+ | || Now, to check whether the '''Blog''' has been created recently, | ||
+ | |||
+ | type- | ||
+ | |||
+ | |||
+ | '''blog dot was underscore created underscore recently opening and closing parentheses''' | ||
+ | |- | ||
+ | || [Terminal]In Output, Highlight | ||
+ | |||
+ | '''True''' | ||
+ | || Here, the result says '''TRUE.''' | ||
+ | |||
+ | This is because '''blog''' was created recently in the''' shell''' few minutes back. | ||
+ | |- | ||
+ | || [Terminal] Type: | ||
+ | |||
+ | blog1.was_created_recently() [Enter] | ||
+ | || Run the '''command''' again for '''variable ‘blog one’.''' | ||
+ | |- | ||
+ | || [Terminal]In Output, Highlight | ||
+ | |||
+ | '''False''' | ||
+ | || Here, the result says '''FALSE '''as first '''blog''' was not recently created. | ||
+ | |||
+ | Note: The above results may vary as per your creation dates. | ||
+ | |- | ||
+ | || [Terminal] Type: | ||
+ | |||
+ | blog2 = Blog.objects.filter(id=2) [Enter] | ||
+ | || Let us do filtering with '''Django Queries''' | ||
+ | |||
+ | Type the command as shown. | ||
+ | |- | ||
+ | || [Terminal] | ||
+ | |||
+ | Highlight | ||
+ | |||
+ | '''blog2 = Blog.objects.filter(id=2)''' | ||
+ | || Here, the '''Queryset''' is evaluated. | ||
+ | |||
+ | |||
+ | Then, we fetch the result of a '''Blog object '''for which the '''id''' is two. | ||
+ | |||
+ | |||
+ | Since the '''id '''is unique, we get only one result. | ||
+ | |- | ||
+ | || [Terminal] Type: '''blog2''' [Enter] | ||
+ | || Let us '''access''' the '''object''', by typing '''blog two.''' | ||
+ | |- | ||
+ | || [Terminal] In Output, Highlight | ||
+ | |||
+ | '''<QuerySet [<Blog: This is a Blog from shell!>]>''' | ||
+ | || The output returns the new '''Queryset''' containing the '''object''' that matches the given parameter. | ||
+ | |||
+ | Here, '''Queryset''' gives the respective '''Blog instances''' for the''' id two.''' | ||
+ | |- | ||
+ | || [Terminal] Type: blog2[0].id [Enter] | ||
+ | || To get the '''id''', type the '''command''' as shown. | ||
+ | |- | ||
+ | || [Terminal] In Output, Highlight '''2''' | ||
+ | || The output shows the '''id''' for the given '''Blog object.''' | ||
+ | |- | ||
+ | || [Terminal] Type: blog2[0] [Enter] | ||
+ | || Now, type '''blog two two within square brackets zero''' | ||
+ | |- | ||
+ | || [Terminal] In Output, Highlight | ||
+ | |||
+ | '''<Blog: This is a Blog from shell!>''' | ||
+ | || In the output, we get the '''blog object'''. | ||
+ | |||
+ | If we want a single blog object and it exists. | ||
+ | |||
+ | |- | ||
+ | || [Terminal] | ||
+ | |||
+ | blog2 = Blog.objects.get(id=2) | ||
+ | |||
+ | || In this case we should use''' get query.''' | ||
+ | |||
+ | To do so, type the command as shown. | ||
+ | |- | ||
+ | || [Terminal] Type: '''blog2''' [Enter] | ||
+ | || Let us '''access''' the '''object''', by typing '''blog two.''' | ||
+ | |- | ||
+ | || [Terminal] In Output, Highlight | ||
+ | |||
+ | '''<Blog: This is a Blog from shell>''' | ||
+ | || It will return the '''Blog object''' referred by its '''id.''' | ||
+ | |||
+ | |- | ||
+ | || | ||
+ | || Let us now try to get the '''Blog objects''' based on the year of creation. | ||
+ | |||
+ | First '''import '''the '''timezone''' from '''django.utils''' | ||
+ | |- | ||
+ | || [Terminal] Type: | ||
+ | |||
+ | current_year = timezone.now().year [Enter] | ||
+ | |||
+ | Blog.objects.filter(created_on__year=current_year) [Enter] | ||
+ | || Then type the code as shown here one by one. | ||
+ | |- | ||
+ | || [Terminal] | ||
+ | |||
+ | Highlight | ||
+ | |||
+ | Blog.objects.filter('''created_on__year=current_year''') | ||
+ | || '''Double underscores''' are used for '''Field Lookups.''' | ||
+ | |||
+ | It returns a new '''Queryset''' containing the '''objects''' that match the given '''lookup parameters.''' | ||
+ | |- | ||
+ | || [Terminal] In Output, Highlight | ||
+ | |||
+ | '''<QuerySet [<Blog: … >, <Blog: ... >]> ''' | ||
+ | || This '''query''' will return all the '''Blog instances''' created in this year. | ||
+ | |- | ||
+ | || [Terminal]Type: | ||
+ | |||
+ | blogs = Blog.objects.all() [Enter] | ||
+ | || Now, let us understand the '''Queryset return method.''' | ||
+ | |||
+ | To do so, type code as shown. | ||
+ | |- | ||
+ | || [Terminal]Type: | ||
+ | |||
+ | blogs.count() [Enter] | ||
+ | || To count the '''Blog objects''', type '''blogs dot count opening and closing parentheses''' | ||
+ | |- | ||
+ | || [Terminal] In Output, Highlight '''2''' | ||
+ | || The output gives the '''count''' of '''Blog objects.''' | ||
+ | |- | ||
+ | || [Terminal] Type Blogs. | ||
+ | |||
+ | (press Tab) | ||
+ | || To know the '''available method '''for the '''Queryset return, '''type '''Blogs dot ''' | ||
+ | |||
+ | Press the '''Tab '''key to see the number of available '''methods.''' | ||
+ | |- | ||
+ | || [Terminal] | ||
+ | |||
+ | (pointing to the shell prompt) | ||
+ | || Here, we can see a list of '''methods''' to return the '''Queryset.''' | ||
+ | |||
+ | Note: These '''methods''' can be directly used with '''objects''' as follows: | ||
+ | |||
+ | '''Blog''' dot '''objects''' dot '''<''method''>''' | ||
+ | |- | ||
+ | || [Terminal]Type: | ||
+ | |||
+ | blog = Blog.objects.get(id=1) [Enter] | ||
+ | || For example, to get a '''Blog Object, '''use the''' get() lookup''' parameter. | ||
+ | |||
+ | Type the '''command''' as shown here. | ||
+ | |- | ||
+ | || [Terminal] Type: | ||
+ | |||
+ | blog.article_set.all() [Enter] | ||
+ | || To get the related '''objects''' to the '''blog''' i.e. '''Articles''', we use '''blog dot article_set dot all''' | ||
+ | |- | ||
+ | || [Terminal] In Output, Highlight | ||
+ | |||
+ | '''<QuerySet [<Article: My Article>]> ''' | ||
+ | || Every '''Article '''is related to a '''Blog '''because of the '''Foreign Key relationship.''' | ||
+ | |- | ||
+ | || [Terminal] Type: | ||
+ | |||
+ | from blog.models import Article | ||
+ | |||
+ | Article = Article.objects.get(id=1) [Enter] | ||
+ | |||
+ | blog1 = Article.blog [Enter] | ||
+ | |||
+ | blog1.id [Enter] | ||
+ | || Also, we can access the information of the '''Blog object '''through it's related '''Article object.''' | ||
+ | |||
+ | |||
+ | To do that, type the following '''command''' one by one as shown here. | ||
+ | |- | ||
+ | || [Terminal] In Output, Highlight '''1''' | ||
+ | || We get '''one''' as the output. | ||
+ | |||
+ | This is our '''Blog object's id.''' | ||
+ | |- | ||
+ | || [Terminal] Type: | ||
+ | |||
+ | blog2.delete() [Enter] | ||
+ | || Now, using '''delete() method''', the '''object''' gets deleted. | ||
+ | |||
+ | Type '''blog two dot delete opening and closing parentheses''' | ||
+ | |- | ||
+ | || [Terminal] | ||
+ | |||
+ | (Pointing to the shell prompt) | ||
+ | |||
+ | In Output, Highlight '''(1, {‘blog.Blog’: 1, ‘blog.Article’: 0}) ''' | ||
+ | || In output, it returns the number of '''objects '''deleted. | ||
+ | |||
+ | |||
+ | And a '''dictionary''' with the number of deletions per '''object type.''' | ||
+ | |- | ||
+ | || [Terminal] | ||
+ | |||
+ | Type Blog.objects.get(id=2) [Enter] | ||
+ | || Then we use '''get '''with '''id two''' by typing | ||
+ | |||
+ | '''Blog dot objects dot get within parentheses id equal to two''' | ||
+ | |- | ||
+ | || [Terminal] | ||
+ | |||
+ | (pointing the Error) | ||
+ | || The output throws '''Exception '''as “'''Blog''' does not exist”. | ||
+ | |||
+ | This indicates that the '''Blog object '''we had created, has been deleted. | ||
+ | |- | ||
+ | || [Terminal] | ||
+ | |||
+ | (pointing the Error) | ||
+ | || '''get query''' will always return a single '''object'''. | ||
+ | |||
+ | |||
+ | If there are more than one match or no match, then it will throw an '''error'''. | ||
+ | |||
+ | In that case, it's advisable to use '''filter.''' | ||
+ | |- | ||
+ | || [Terminal] Type: | ||
+ | |||
+ | Blog.objects.filter(id=2) [Enter] | ||
+ | || Let us do '''filtering '''with '''id two''' by typing | ||
+ | |||
+ | '''Blog dot objects dot filter within parentheses id equal to two''' | ||
+ | |- | ||
+ | || In Output, Highlight '''<QuerySet []>''' | ||
+ | || The result is a''' Null Queryset.''' | ||
+ | |- | ||
+ | || | ||
+ | || So, we have learnt to create a '''Django Database Query''' using '''Django Shell.''' | ||
+ | |- | ||
+ | || Terminal] Press Ctrl+C keys | ||
+ | |||
+ | Type deactivate [Enter] | ||
+ | || Exit from the '''shell'''. | ||
+ | |||
+ | Deactivate the '''virtual environment.''' | ||
+ | |- | ||
+ | || Switch to slide | ||
+ | || With this, we come to the end of this tutorial | ||
+ | |||
+ | Let us summarize. | ||
+ | |- | ||
+ | || Slide: Summary | ||
+ | || In this tutorial, we have learnt to | ||
+ | * Use the '''Django shell '''and | ||
+ | * Create a '''Django Query''' | ||
+ | |||
+ | |- | ||
+ | || Slide: Assignment | ||
+ | || As an assignment, | ||
+ | |||
+ | * Create and access an''' Article object''' within '''Blog model''' using '''Django Query''' in '''Shell''' | ||
+ | |||
+ | |- | ||
+ | || Slide: About Spoken Tutorial project | ||
+ | || The video at the following link summarises the Spoken Tutorial project. | ||
+ | |||
+ | Please download and watch it. | ||
+ | |- | ||
+ | || Slide: Spoken Tutorial workshops | ||
+ | || The '''Spoken Tutorial Project''' team conducts workshops and gives certificates. | ||
+ | |||
+ | |||
+ | For more details, please write to us. | ||
+ | |- | ||
+ | || Slide: Forum for specific questions: | ||
+ | || Please post your timed queries in this Forum. | ||
+ | |- | ||
+ | || Slide: FOSSEE to answer questions | ||
+ | || Please post your general or technical questions in this Forum. | ||
+ | |- | ||
+ | || Slide: Acknowledgement | ||
+ | || Spoken Tutorial Project is funded by NMEICT, MHRD, Government of India. | ||
+ | |||
+ | |||
+ | More information on this mission is available at this link. | ||
+ | |- | ||
+ | || Slide: Thanks Slide | ||
+ | || This script has been contributed by Thiagarajar College of Engineering and the FOSSEE Project, IIT Bombay. | ||
+ | |||
+ | The video has been recorded by Praveen from Spoken Tutorial Project, IIT Bombay. | ||
+ | |||
+ | Thanks for watching. | ||
+ | |- | ||
+ | |} |
Latest revision as of 12:01, 28 June 2019
Django/C2/Django_Shell_and_Django_Database_Query/English
Title of script: Django Shell and Django Database Query
Keywords: Video tutorial, Django Shell, Django Database Query
Visual cue | Narration |
Slide: Django Shell and Django Database Query | Hello and welcome to the spoken tutorial on “Django Shell and Django Database Query”. |
Slide: Learning Objectives | In this tutorial, we will learn to:
|
Slide: System Requirements | To practice this tutorial, I am using
However, you can use any other text editor of your choice. |
Slide: Prerequisites | To follow this tutorial, you need to know
|
Slide: What is the Django Shell ? |
|
Open a Terminal window
Press CTRl+ALT+T simultaneously |
Let us open the terminal by pressing Ctrl, Alt and T keys simultaneously on your keyboard. |
[Terminal]
cd my-django [Enter] |
Now using cd command, we will go to the folder my hyphen django which we had created earlier. |
[Terminal]
Type source myapp_env/bin/activate [Enter] |
Activate the virtual environment myapp underscore env |
[Terminal]
cd mysite and Press Enter |
Now let us go to the folder mysite. |
Here onwards, please remember to press the Enter key after typing each command. | |
[Terminal]
Type python manage.py shell [Enter] |
Let us now type the command-
python manage dot py <space> shell |
[Terminal]
Highlight (point to the shell) (InteractiveConsole) >>> |
We are now in the Interactive console. |
Slide: Interactive console |
|
Switch to Terminal | Switch back to terminal. |
[Terminal]Type:
from blog.models import Blog [Enter] from django.utils import timezone [Enter] blog = Blog(name='My Second Blog', created_on=timezone.now()) [Enter] blog.save() [Enter] |
Let us run a Django query to add a new Blog.
Type the commands one by one as shown here. |
[Terminal]
Highlight from blog.models import Blog |
To add a new Blog, we need to import Blog from our models. |
[Terminal]
Highlight blog = Blog(name='My Second Blog', created_on=timezone.now()) |
Here we have created a Blog instance. |
[Terminal]
Highlight blog = Blog(name='My Second Blog', created_on=timezone.now()) |
Also, we have added values to its fields - name and creation date. |
[Terminal]
Highlight created_on=timezone.now() |
created_on attribute is not needed while creating a new blog object.
|
[Terminal]
Highlight from django.utils import timezone |
To get the creation date, we import timezone from django dot utils module. |
[Terminal]
Highlight blog.save() |
Then, save the object that we have created.
So, Django writes this information to the database table Blog. |
[Terminal] Type:
blog.id [Enter] |
Let's now access the model field values through Python attributes.
To do so, type blog dot id |
[Terminal]
In Output, Highlight 2 |
Here, the output shows two.
It is the id of the Blog object that we have created now. |
[Terminal]
Type blog.name [Enter] |
To display the name of the Blog object, type blog dot name |
[Terminal]
In Output, Highlight 'My Second Blog' |
Our Blog object name 'My Second Blog' is being displayed. |
[Terminal]
Type blog.created_on [Enter] |
To see the date time values of our Blog object, type
blog dot created underscore on |
[Terminal]
In Output, Highlight datetime.datetime(....) |
Here, it shows the date and time when the Blog was created. |
[Terminal]
Type: blog.name = 'This is a blog from shell' [Enter] |
Let us now change the name of our Blog object.
|
[Terminal] Highlight
blog.name = 'This is a Blog from shell' |
This will change the name in the output as This is a Blog from shell. |
[Terminal] Type blog.save() [Enter] | Save the blog. |
[Terminal] Type blog.name [Enter] | Then recall the blog dot name command and execute it. |
[Terminal] In Output, Highlight
'This is a Blog from shell' |
We can see the name as 'This is a Blog from shell'
|
[Terminal]
Blog.objects.all() [Enter] |
To get all Blog objects using Query, type
|
[Terminal] In Output, Highlight
<QuerySet [<Blog: Blog object (1)>, <Blog: Blog object (2)>]> |
In the output, we can see the Queryset with a list of Blog objects.
|
[Terminal]
|
Let us fix this in the models.py file.
|
[Terminal]
|
Then open the models.py file in any text editor. |
[blog/models.py]
# Create your models here. class Blog(models.Model): name = models.CharField(max_length=120) created_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Article(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE) created_on = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=120) body = models.TextField() draft = models.BooleanField(default=False) def __str__(self): return self.title |
We are now in the models.py file.
|
[models.py]
Highlight def __str__(self): |
We define a String method inside the class to get string representation of the object. |
[models.py]
Highlight return self.name |
Here, the String method returns the name of our Blog model. |
[models.py]
Highlight return self.title |
Similarly, for the Article model, let’s return the title. |
[models.py]
Highlight the complete code |
We have added the string method.
So now when we retrieve a Blog object, we will see its name. Lets understand this better. |
Press Ctrl+S | Save the file. |
Switch to Terminal | Then switch to the terminal. |
[Terminal] Type:
python manage.py shell [Enter] |
And activate the Shell. |
[Terminal]In Shell, Type:
from blog.models import Blog [Enter] |
Import the blog models. |
[Terminal]In Shell, Type:
Blog.objects.all() [Enter] |
And run the Django Query as we did before. |
[Terminal] In Output, Highlight
<QuerySet[...<Blog: This is a blog from shell!...']> |
It returns all the instances of the Blog model along with its name. |
[Terminal]
|
Now, let's add a custom method to the Blog model in models.py file.
|
Switch to models.py file | Switch to the models.py file. |
[models.py]
from django.db import models from django.utils import timezone # Create your models here. class Blog(models.Model): name = models.CharField(max_length=120) created_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name def was_created_recently(self): return self.created_on >= timezone.now() - timezone.timedelta(days=1) |
Now, modify the class Blog as shown here.
|
[models.py] Highlight timezone.now() | timezone.now() returns a date time that represents the current time. |
[models.py] Highlight timezone.timedelta | timedelta expresses the duration difference between
|
[models.py] Highlight
from django.utils import timezone |
To store timezone information, we import package timezone from django dot utils module. |
[models.py]
Highlight def was_created_recently(self): return self.created_on >= timezone.now() - timezone.timedelta(days=1) |
The "method was created recently” checks whether the Blog is created more recent than a day.
|
[models.py] Highlight the complete code | So we have added the method to Blog. |
Press Ctrl+S | Save the file. |
Switch to Terminal | Switch to the terminal. |
[Terminal] Type:
python manage.py shell [Enter] |
And activate the shell. |
[Terminal] In Shell, Type:
from blog.models import Blog [Enter] |
Import the blog models. |
blog = Blog.objects.get(name=”This is a Blog from shell!”) [Enter]
|
The variable ‘blog’ has been lost as we quit from the shell to modify our model.
|
[Terminal] Type:
blog.was_created_recently() [Enter] |
Now, to check whether the Blog has been created recently,
type-
|
[Terminal]In Output, Highlight
True |
Here, the result says TRUE.
This is because blog was created recently in the shell few minutes back. |
[Terminal] Type:
blog1.was_created_recently() [Enter] |
Run the command again for variable ‘blog one’. |
[Terminal]In Output, Highlight
False |
Here, the result says FALSE as first blog was not recently created.
Note: The above results may vary as per your creation dates. |
[Terminal] Type:
blog2 = Blog.objects.filter(id=2) [Enter] |
Let us do filtering with Django Queries
Type the command as shown. |
[Terminal]
Highlight blog2 = Blog.objects.filter(id=2) |
Here, the Queryset is evaluated.
|
[Terminal] Type: blog2 [Enter] | Let us access the object, by typing blog two. |
[Terminal] In Output, Highlight
<QuerySet [<Blog: This is a Blog from shell!>]> |
The output returns the new Queryset containing the object that matches the given parameter.
Here, Queryset gives the respective Blog instances for the id two. |
[Terminal] Type: blog2[0].id [Enter] | To get the id, type the command as shown. |
[Terminal] In Output, Highlight 2 | The output shows the id for the given Blog object. |
[Terminal] Type: blog2[0] [Enter] | Now, type blog two two within square brackets zero |
[Terminal] In Output, Highlight
<Blog: This is a Blog from shell!> |
In the output, we get the blog object.
If we want a single blog object and it exists. |
[Terminal]
blog2 = Blog.objects.get(id=2) |
In this case we should use get query.
To do so, type the command as shown. |
[Terminal] Type: blog2 [Enter] | Let us access the object, by typing blog two. |
[Terminal] In Output, Highlight
<Blog: This is a Blog from shell> |
It will return the Blog object referred by its id. |
Let us now try to get the Blog objects based on the year of creation.
First import the timezone from django.utils | |
[Terminal] Type:
current_year = timezone.now().year [Enter] Blog.objects.filter(created_on__year=current_year) [Enter] |
Then type the code as shown here one by one. |
[Terminal]
Highlight Blog.objects.filter(created_on__year=current_year) |
Double underscores are used for Field Lookups.
It returns a new Queryset containing the objects that match the given lookup parameters. |
[Terminal] In Output, Highlight
<QuerySet [<Blog: … >, <Blog: ... >]> |
This query will return all the Blog instances created in this year. |
[Terminal]Type:
blogs = Blog.objects.all() [Enter] |
Now, let us understand the Queryset return method.
To do so, type code as shown. |
[Terminal]Type:
blogs.count() [Enter] |
To count the Blog objects, type blogs dot count opening and closing parentheses |
[Terminal] In Output, Highlight 2 | The output gives the count of Blog objects. |
[Terminal] Type Blogs.
(press Tab) |
To know the available method for the Queryset return, type Blogs dot
Press the Tab key to see the number of available methods. |
[Terminal]
(pointing to the shell prompt) |
Here, we can see a list of methods to return the Queryset.
Note: These methods can be directly used with objects as follows: Blog dot objects dot <method> |
[Terminal]Type:
blog = Blog.objects.get(id=1) [Enter] |
For example, to get a Blog Object, use the get() lookup parameter.
Type the command as shown here. |
[Terminal] Type:
blog.article_set.all() [Enter] |
To get the related objects to the blog i.e. Articles, we use blog dot article_set dot all |
[Terminal] In Output, Highlight
<QuerySet [<Article: My Article>]> |
Every Article is related to a Blog because of the Foreign Key relationship. |
[Terminal] Type:
from blog.models import Article Article = Article.objects.get(id=1) [Enter] blog1 = Article.blog [Enter] blog1.id [Enter] |
Also, we can access the information of the Blog object through it's related Article object.
|
[Terminal] In Output, Highlight 1 | We get one as the output.
This is our Blog object's id. |
[Terminal] Type:
blog2.delete() [Enter] |
Now, using delete() method, the object gets deleted.
Type blog two dot delete opening and closing parentheses |
[Terminal]
(Pointing to the shell prompt) In Output, Highlight (1, {‘blog.Blog’: 1, ‘blog.Article’: 0}) |
In output, it returns the number of objects deleted.
|
[Terminal]
Type Blog.objects.get(id=2) [Enter] |
Then we use get with id two by typing
Blog dot objects dot get within parentheses id equal to two |
[Terminal]
(pointing the Error) |
The output throws Exception as “Blog does not exist”.
This indicates that the Blog object we had created, has been deleted. |
[Terminal]
(pointing the Error) |
get query will always return a single object.
In that case, it's advisable to use filter. |
[Terminal] Type:
Blog.objects.filter(id=2) [Enter] |
Let us do filtering with id two by typing
Blog dot objects dot filter within parentheses id equal to two |
In Output, Highlight <QuerySet []> | The result is a Null Queryset. |
So, we have learnt to create a Django Database Query using Django Shell. | |
Terminal] Press Ctrl+C keys
Type deactivate [Enter] |
Exit from the shell.
Deactivate the virtual environment. |
Switch to slide | With this, we come to the end of this tutorial
Let us summarize. |
Slide: Summary | In this tutorial, we have learnt to
|
Slide: Assignment | As an assignment,
|
Slide: About Spoken Tutorial project | The video at the following link summarises the Spoken Tutorial project.
Please download and watch it. |
Slide: Spoken Tutorial workshops | The Spoken Tutorial Project team conducts workshops and gives certificates.
|
Slide: Forum for specific questions: | Please post your timed queries in this Forum. |
Slide: FOSSEE to answer questions | Please post your general or technical questions in this Forum. |
Slide: Acknowledgement | Spoken Tutorial Project is funded by NMEICT, MHRD, Government of India.
|
Slide: Thanks Slide | This script has been contributed by Thiagarajar College of Engineering and the FOSSEE Project, IIT Bombay.
The video has been recorded by Praveen from Spoken Tutorial Project, IIT Bombay. Thanks for watching. |