Today I Learned/django

(장고) ORM tutorial #1. all(), get() , filter(), save(), delete()

하나719 2023. 8. 21. 13:38
반응형

https://www.pythontutorial.net/django-tutorial/django-orm/

 

Django ORM

In this tutorial, you'll learn about Django ORM and how to use Django ORM API to interact with relational databases.

www.pythontutorial.net

장고의 ORM을 잘 이해하기 위해 튜토리얼 진행

 

1. postgreSql 사용을 위한 패키지 설치 및 설정

pip install psycopg2

 

settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'hr',
        'USER': 'postgres',
        'HOST': 'localhost',
        'PORT': '',
    }
}

2. hr 앱의 models.py 에 Employee 모델 생성 및 정의

hr > models.py

class Employee(models.Model):
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)

    def __str__(self):
        return f'{self.first_name} {self.last_name}'

+ 마이그레이션 해주기

3. shell_plus 설치 및 설정 , 열기

shell_plus는 django-extensions 를 설치하면 사용가능 

 

설치: pip install django-extensions 

설정: settings.py > INSTALLED_APPS 에 추가

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'hr.apps.HrConfig',
    ## 추가 ##
    'django_extensions',
]

열기: python manage.py shell_plus --print-sql

4. Employee 모델에 데이터 넣고 다루기

# 추가 1
e = Employee(first_name = 'Choi', last_name = 'hana')
e.save() 
# 추가 2
e = Employee(first_name = 'Choi', last_name = 'duri')
e.save()

# 모든 행 불러오기
Employee.objects.all() 

# id로 하나만 가져오기
e = Employee.objects.get(id=1)
e

# filter로 특정 행 가져오기
e = Employee.objects.filter(last_name = 'hana')
e 

# 데이터 업데이트 하기
e = Employee.objects.get(id=1)
e.last_name = 'Joey'
e.save() 

# 데이터 삭제하기 
e.delete()

[결과 화면 참고]

- all () : querySet으로 return 

- get() : Employee 객체로 Return 

- filter(): querySet으로 return 

- save() : 데이터 수정 -> 객체에 할 수 있고, 쿼리셋에 적용 안됨 

 

 

반응형