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```.
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)
>>>
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.
queryset
The name comes out, but it seems that a query set is a list of objects provided by the model.
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.
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=ryosuke
I got an error.
author
It 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 of
admin``` 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```.
To extract a specific condition, use filter ()` `` for the part that was
all ()` `` 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>]>
title
To__contains
By 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.
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.
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 of
order_by.
ascOr
desc```Isn't it (I think it also supports this area).
Now you can sort.
Sometimes I launch the console, but at first I don't know how to exit it.
>>> exit()
Don't forget this last `()`
.
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