Easy-to-understand explanation of Python Web application (Django) even for beginners (5) [Introduction to DB operation with Django shell]

Composition of commentary articles

No. title
1 Easy-to-understand explanation of Python Web application (Django) even for beginners (1) [Environment construction]
2 Easy-to-understand explanation of Python Web application (Django) even for beginners (2) [Project creation]
3 Easy-to-understand explanation of Python Web application (Django) even for beginners (3) [Application creation / DB setting]
4 Easy-to-understand explanation of Python web application (Django) even for beginners (4) [Routing settings / Introduction to MTV design patterns]
5 Easy-to-understand explanation of Python Web application (Django) even for beginners (5) [Introduction to DB operation with Django shell]
6 Easy-to-understand explanation of Python web application (Django) even for beginners (6) [MTV design pattern completion]

Development environment

We will proceed on the premise of a Mac environment.

Check the Python version as follows.

$ python3 --version
Python 3.5.2

Django shell

This time, I'll show you how to use `` `Django shell```.

Last time, I showed you how to use Django admin to manipulate and check your DB. If you are accustomed to Ruby on Rails, why not use `rails c``` on such a console to operate and check? I'm sure there are people who think that, but I think that's right. Django also has such a console, which is `Django shell```.

Let's use Django shell

First, launch `` `Django shell```.

Launch Django


$ python3 manage.py shell
Python 3.5.2 (default, Jun 29 2016, 13:43:58) 
[GCC 4.2.1 Compatible Apple LLVM 7.3.0 (clang-703.0.31)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> 

Let's display the data with Django shell

Now let's take a look at the data of the defined model `` `Post```.

>>> Post.objects.all()
Traceback (most recent call last):
  File "<console>", line 1, in <module>
NameError: name 'Post' is not defined

Unfortunately, I got an error (though I didn't get an error if I followed the same procedure as Ruby on Rails). Django seems to have to import the model first.

>>> from blog.models import Post
>>> Post.objects.all()
<QuerySet [<Post:Sample article title>]>

Now you can check the data in the DB. querysetThe name comes out, but it seems that a query set is a list of objects provided by the model.

Coffee Break: Compare Django with Ruby on Rails

As you may have noticed in previous articles, Django is because I learned Ruby on Rails as the very first web framework and it has become my standard. In some places, I get the impression that it's harder to use than Ruby on Rails. However, Python web frameworks are very attractive for using machine learning. Personally, I recommend Ruby on Rails as the foundation for your web application and Django as your web API.

Let's create an object with Django shell

Create a new Post in the database.

>>> Post.objects.create(author=ryosuke, title="ryosuke's article", text="This is an article for Qiita")
Traceback (most recent call last):
  File "<console>", line 1, in <module>
NameError: name 'ryosuke' is not defined

You got an error. author=ryosukeI got an error. authorIt doesn't increase by the specified name. .. ..

Actually, when I made a model with Django (Explanation of Python Web application (Django) in an easy-to-understand manner (3): Creating a model #% E3% 83% A2% E3% 83% 87% E3% 83% AB% E3% 81% AE% E4% BD% 9C% E6% 88% 90)), `blog / models.py` Within

blog/models.Part of py


author = models.ForeignKey('auth.User')

This is because it is set to refer to the User model. If you simply define this as a character string, you can create an object for a new name without any problems. However, this makes it difficult to manage user names, so we manage users as users and posts as posts so that posts refer to users.

This time, we will not create a new user, but give the user `` `ryosukethe information ofadmin``` and create a new object from there.

Give ryosuke admin information


>>> from django.contrib.auth.models import User
>>> User.objects.all()
<QuerySet [<User: admin>]>
>>> ryosuke = User.objects.get(username='admin')
>>> ryosuke
<User: admin>

Create a new object in Post


>>> Post.objects.create(author=ryosuke, title="ryosuke's article", text="This is an article for Qiita")
<Post: ryosuke's article>

This worked. Let's take a look at the Post object list.

>>> Post.objects.all()
<QuerySet [<Post:Sample article title>, <Post: ryosuke's article>]>

You can see that there are more new `` `Post```.

Let's extract objects with specific conditions with Django shell

To extract a specific condition, use filter ()` `` for the part that wasall ()` `` and give property information to the argument. For example, to extract only Posts with author = ryosuke, it will be as follows.

>>> Post.objects.filter(author=ryosuke)
<QuerySet [<Post:Sample article title>, <Post: ryosuke's article>]>

For now, it's no different from all objects, but if you have more author, you can separate them by author in this way.

In addition to extracting conditions that match exactly, you can also search for partial matches that include a specific character string in part.

Extract only objects that include article in title


>>> Post.objects.filter(title__contains='article')
<QuerySet [<Post: ryosuke's article>]>

titleTo__containsBy adding, you will be able to handle partial matches well (this is quite convenient).

In Python, there are often two underscores for the above. Reference: Django Girls Tutorial: Query Set 1

Note There are two underscores between title and contains, which is Django's ORM syntax. The title of the field name and the contents of the collation type are concatenated with two underscores. If there is only one underscore, it will be judged as the field name title_contains and an error will occur. ("FieldError: Cannot resolve keyword title_contains")

Next, this is also a frequently used function, but it is a method to extract only articles that have already been published. Qiita also creates articles, but it may be left as a draft. This is the method when you want to extract only published at this current time.

>>> from django.utils import timezone
>>> Post.objects.filter(published_date__lte=timezone.now())
<QuerySet [<Post:Sample article title>]>

As you may know, the `lte``` part is the condition for writing a filter like contain```. ```lte```Is```less than or equal to```Abbreviation for "published" in mathematical symbols_date <=It means "current time". It is a condition that extracts before the current time or if it matches the current time. The object I just added from the Django shell didn't set `` published_date```, so this condition doesn't apply.

Since we often use one underscore for variable names, we use two underscores in Django's ORM syntax. If there is only one underscore, it will be treated as a variable name, resulting in a " FieldError: Cannot resolve keyword title_contains " error.

Update the contents of the object

The object you just created hasn't been published (`` `publish```) yet, so let's publish it.

Get the created model


post = Post.objects.get(id=2)
>>> post
<Post: ryosuke's article>

blog/models.publish with py()Since the method is defined as follows, it is easy to publish using this method._You can update the value of date.




#### **`blog/models.py`**
```py

def publish(self):
    self.published_date = timezone.now()
    self.save()

Now, let's use this `publish ()` method.

>>> post.publish()
>>> Post.objects.filter(published_date__lte=timezone.now())
<QuerySet [<Post:Sample article title>, <Post: ryosuke's article>]>

You have successfully published the article.

Sorting the list of objects

Finally, let's know how to use the rearrangement easily. Web pages are often sorted by amount or date and time, so I think this is a frequently used command.

Use ```order_by ()` `` for sorting.

>>> Post.objects.order_by('created_date')
<QuerySet [<Post:Sample article title>, <Post: ryosuke's article>]>

Basically, if it is a date and time, it will be arranged in chronological order. If you want to sort in the order of newly added, you can specify this reverse order as follows.

>>> Post.objects.order_by('-created_date')
<QuerySet [<Post: ryosuke's article>, <Post:Sample article title>]>

The idea is to add `` `-to the argument oforder_by. ascOrdesc```Isn't it (I think it also supports this area).

Now you can sort.

Exit Django shell

Sometimes I launch the console, but at first I don't know how to exit it.

>>> exit()

Don't forget this last `()`.

Next commentary article

Explanation of Python Web application (Django) in an easy-to-understand manner even for beginners (6) [MTV design pattern completion]

References

bonus

We are waiting for you to follow us!

Service introduction Please feel free to contact us if you are interested in "Kikagaku", a one-on-one tutoring service for machine learning that allows you to learn "math-> programming-> web applications" all at once.

Recommended Posts

Easy-to-understand explanation of Python Web application (Django) even for beginners (5) [Introduction to DB operation with Django shell]
Easy-to-understand explanation of Python Web application (Django) even for beginners (3) [Application creation / DB setting]
Easy-to-understand explanation of Python web application (Django) even for beginners (4) [Routing settings / Introduction to MTV design patterns]
Easy-to-understand explanation of Python Web application (Django) even for beginners (2) [Project creation]
Easy-to-understand explanation of Python Web application (Django) even for beginners (1) [Environment construction]
Easy-to-understand explanation of Python web application (Django) even for beginners (6) [MTV design pattern completion]
[For beginners] Summary of standard input in Python (with explanation)
[Introduction to Udemy Python3 + Application] 17. List operation
[For beginners] Try web scraping with Python
Updated "Introduction to Python Web Application Homebrew for Slow 3rd Year Web Engineers"
Updated "Introduction to Python Web Application Homebrew for Slow 3rd Year Web Engineers"
Updated "Introduction to Python Web Application Homebrew for Slow 3rd Year Web Engineers"
[Introduction to Udemy Python3 + Application] 47. Process the dictionary with a for statement
Updated "Introduction to Python Web Application Homebrew for Slow 3rd Year Web Engineers"
Explanation of creating an application for displaying images and drawing with Python
Updated "Introduction to Python Web Application Homebrew for Slow 3rd Year Web Engineers"
Updated "Introduction to Python Web Application Homebrew for Slow 3rd Year Web Engineers"
[Introduction to Udemy Python 3 + Application] 26. Copy of dictionary
[Introduction to Udemy Python 3 + Application] 19. Copy of list
[Introduction to Udemy Python3 + Application] 43. for else statement
[Introduction to Udemy Python3 + Application] 9. First, print with print
Introduction to Programming (Python) TA Tendency for beginners
[Introduction for beginners] Working with MySQL in Python
[Introduction to Python] How to get the index of data with a for statement
A super introduction to Django by Python beginners! Part 5 I made a super simple diary application with a class-based general-purpose view
(Python) Try to develop a web application using Django
[Chapter 5] Introduction to Python with 100 knocks of language processing
[Introduction to Udemy Python3 + Application] 53. Dictionary of keyword arguments
Web application made with Python3.4 + Django (Part.1 Environment construction)
[Chapter 3] Introduction to Python with 100 knocks of language processing
[Python] Introduction to web scraping | Summary of methods that can be used with webdriver
[For beginners] Web scraping with Python "Access the URL in the page to get the contents"
[Chapter 2] Introduction to Python with 100 knocks of language processing
Beginners try to make an online battle Othello web application with Django + React + Bootstrap (1)
[Cloud9] Try to build an environment with django 1.11 of Python 3.4 without understanding even 1 mm
[Introduction to Udemy Python3 + Application] 52. Tupleization of positional arguments
Explanation of NoReverseMatch error in "python django super introduction"
Beginners use Python for web scraping (4) --2 Scraping on Cloud Shell
[Chapter 4] Introduction to Python with 100 knocks of language processing
[Introduction to Udemy Python3 + Application] 42. for statement, break statement, and continue statement
■ Kaggle Practice for Beginners --Introduction of Python --by Google Colaboratory
[Explanation for beginners] Introduction to convolution processing (explained in TensorFlow)
[Explanation for beginners] Introduction to pooling processing (explained in TensorFlow)
[Ipdb] Web development beginners tried to summarize debugging with Python
Try to automate the operation of network devices with Python
Introduction to Python for VBA users-Calling Python from Excel with xlwings-
Web application with Python3.3.1 + Bottle (1) --Change template engine to jinja2
[Raspi4; Introduction to Sound] Stable recording of sound input with python ♪
[Python] Introduction to graph creation using coronavirus data [For beginners]
(For beginners) Try creating a simple web API with Django
[Introduction to Udemy Python3 + Application] 51. Be careful with default arguments
Introduction to Python Django (2) Win
Web application creation with Django
Web application with Python + Flask ② ③
~ Tips for beginners to Python ③ ~
Introduction to Python For, While
Web application with Python + Flask ④
[Python] What is a slice? An easy-to-understand explanation of how to use it with a concrete example.
IPynb scoring system made with TA of Introduction to Programming (Python)
If you know Python, you can make a web application with Django
The story of making a standard driver for db with python.