본문 바로가기

Django

Python Shell 이용하여 명령어 실행시키기

반응형

 

1. shell로 들어가자

$ python manage.py shell
Python 3.8.5 (v3.8.5:580fbb018f, Jul 20 2020, 12:11:27) 
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
 

2. model을 가져와서 지금 들어 있는 Query set이 얼마나 있는지 확인하자

>>> from HelloWorld.models import Post
>>> Post.objects.all()
<QuerySet []>
 

3. 저장된 Query가 없으니 하나 넣어서 잘 들어갔는지 확인해 보자

>>> post = Post(post_title="This is a Blog Title", post_subtitle="This is a Blog Subtitle", post_contents="This is a content.")
>>> post.save()
>>> post.id
1
>>> post.post_title
'This is a Blog Title'
>>> post.post_subtitle
'This is a Blog Subtitle'
>>> post.post_contents
'This is a content.'
 

4. 저장된 내용을 변경해 보자

>>> post.post_contents = "This is my contents"
>>> post.save()
>>> Post.objects.all()
<QuerySet [<Post: Post object (1)>]>
>>> post.post_contents
'This is my contents'
 

5. Post Object 상태보기

>>> Post.objects.all()
<QuerySet [<Post: Post object (1)>]>
 

6. 5번 처럼 Object 갯수만 보여주면 Post가 뭔지 모르므로 Post table에 별명을 지어주기 위해 model.py에 __str__(self) method를 추가하자

import datetime
from django.db import models
from django.utils import timezone

# Create your models here.
class Post(models.Model):
    post_title = models.CharField(max_length=200)
    post_subtitle = models.CharField(max_length=200)
    post_contents = models.CharField(max_length=3000)

    def __str__(self):
        return self.post_title
 

7. 다시 명령어 실행 결과

>>> Post.objects.all()
<QuerySet [<Post: This is a Blog Title>]>
 

 

 

반응형

'Django' 카테고리의 다른 글

Visual Studio Code에서 Django Debug Mode  (0) 2022.02.08
django db admin 계정 사용하기. create user  (0) 2022.02.08
Django Model 생성하기  (0) 2022.02.08
Django sqlite3 기초  (0) 2022.02.08
Django에서 Static File 읽어오기  (0) 2022.02.08