본문 바로가기

Python/Django

[Django] DB - Create(Insert), Read

이번에는 데이터베이스에서 CRUD 중 생성 및 삽입, 읽기에 대해서 알아보겠습니다(업데이트, 삭제는 다음에~).

 

 

  • Create/Insert

.save() 메서드 - SQL 데이터베이스에 대한 삽입

.objects.create()를 호출하기만 하면 생성하고 푸시하여 실제 데이터베이스에 저장합니다.

.objects.bulk_create() 메서드 - 한 번의 호출로 여러 개의 새 데이터 엔트리를 대량으로 생성

 

(django) ~\my_site>python manage.py shell
Python 3.10.4 | packaged by conda-forge | (main, Mar 30 2022, 08:38:02) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> print('hello')
hello
>>> 
>>> from office.models import Patient
>>> carl = Patient(first_name='carl', last_name='smith', age=30)
>>> carl.age
30
>>> 
>>> carl.age < 20
------------------------------------------------------------------------------
>>> carl.save()
>>>
>>> Patient.objects.create(first_name='susam', last_name='smith', age=40)
<Patient: Patient object (2)>
>>>
>>> Patient.objects.create(first_name='mimi', last_name='bolus', age=36)
<Patient: Patient object (3)>
>>>
>>> mylist=[Patient(first_name='adam', last_name='smith', age=40),
... Patient(first_name='karl', last_name='marx', age=40),
... Patient(first_name='edward', last_name='gou', age=40)
... ]
>>>
>>> Patient.objects.bulk_create(mylist)
[<Patient: Patient object (4)>, <Patient: Patient object (5)>, <Patient: Patient object (6)>]

 

 

주의) bulk_create() 는 너무 많은 관계에서는 작동하지 않습니다.

 

 

  • Read

.all() - 특정 테이블의 모든 데이터를 가져오기

.get()

.filter()

.exclude()

 

 

.all() 예시

 

(django) ~\my_site>python manage.py shell
Python 3.10.4 | packaged by conda-forge | (main, Mar 30 2022, 08:38:02) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from office.models import Patient
>>>
>>> Patient.objects.all()[0]
<Patient: Patient object (1)>
>>>
>>> print(Patient.objects.all()[0])
Patient object (1)

 

 

가식성을 높이기 위해서 models.py 의 Patient 클래스에 아래 함수를 추가한다.

 

    def __str__(self):
        return f"{self.last_name}, {self.first_name} is {self.age} years old."

 

새로운 코드를 추가하면 shell 을 중지하고 다시 실행해야 한다.

 

(django) ~\my_site>python manage.py shell
Python 3.10.4 | packaged by conda-forge | (main, Mar 30 2022, 08:38:02) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>>
>>> from office.models import Patient
>>>
>>> Patient.objects.all()
<QuerySet [<Patient: smith, carl is 30 years old.>, <Patient: smith, susam is 40 years old.>, <Patient: bolus, mimi is 36 years old.>, <Patient: smith, adam is 40 years old.>, <Patient: marx, karl is 40 years old.>, <Patient: gou, edward is 40 years old.>]>
>>>
>>> Patient.objects.all()[0]
<Patient: smith, carl is 30 years old.>

 

 

 

.Get() 예시 - 단일 결과만 반영되는 경우, 여러 결과가 반영되면 오류가 발생한다.

.Filter() 예시 - 여러 결과가 반영되는 경우, all() 옵션은 없어도 무방하다.

 

(django) ~\my_site>python manage.py shell
Python 3.10.4 | packaged by conda-forge | (main, Mar 30 2022, 08:38:02) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> 
>>> from office.models import Patient
>>> 
>>> Patient.objects.get(pk=1)
<Patient: smith, carl is 30 years old.>
>>> 

>>> Patient.objects.get(first_name='smith')
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "C:\Users\MIKE-mini\.conda\envs\django\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\MIKE-mini\.conda\envs\django\lib\site-packages\django\db\models\query.py", line 650, in get
    raise self.model.DoesNotExist(
office.models.Patient.DoesNotExist: Patient matching query does not exist.
>>> 
>>> Patient.objects.get(last_name='smith')  
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "C:\Users\MIKE-mini\.conda\envs\django\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\MIKE-mini\.conda\envs\django\lib\site-packages\django\db\models\query.py", line 653, in get
    raise self.model.MultipleObjectsReturned(
office.models.Patient.MultipleObjectsReturned: get() returned more than one Patient -- it returned 3!
>>>

>>> Patient.objects.filter(last_name='smith')
<QuerySet [<Patient: smith, carl is 30 years old.>, <Patient: smith, susam is 40 years old.>, <Patient: smith, adam is 40 years old.>]>
>>>
>>> Patient.objects.filter(last_name='smith').all()
<QuerySet [<Patient: smith, carl is 30 years old.>, <Patient: smith, susam is 40 years old.>, <Patient: smith, adam is 40 years old.>]>
>>>

>>> Patient.objects.filter(last_name='smith').filter(age=40).all()
<QuerySet [<Patient: smith, susam is 40 years old.>, <Patient: smith, adam is 40 years old.>]>
>>>

 

 

 

.Q() 예시 - or(|) and (&)

 

>>> from django.db.models import Q
>>>

>>> Patient.objects.filter(last_name='smith').filter(age=40)
<QuerySet [<Patient: smith, susam is 40 years old.>, <Patient: smith, adam is 40 years old.>]>
>>>
>>> Patient.objects.filter(Q(last_name='smith')&Q(age=40))
<QuerySet [<Patient: smith, susam is 40 years old.>, <Patient: smith, adam is 40 years old.>]>
>>>

 

 

 

.Lookup() 예시 - greater than, less than, Starts with

 

>>> Patient.objects.filter(last_name__startswith="s")       
<QuerySet [<Patient: smith, carl is 30 years old.>, <Patient: smith, susam is 40 years old.>, <Patient: smith, adam is 40 years old.>]>
>>>
>>> Patient.objects.filter(last_name__startswith="s").all()
<QuerySet [<Patient: smith, carl is 30 years old.>, <Patient: smith, susam is 40 years old.>, <Patient: smith, adam is 40 years old.>]>
>>>
>>> Patient.objects.filter(age__in=[20,30,40])             
<QuerySet [<Patient: smith, carl is 30 years old.>, <Patient: smith, susam is 40 years old.>, <Patient: smith, adam is 40 years old.>, <Patient: marx, karl is 40 years old.>, <Patient: gou, edward is 40 years old.>]>
>>>
>>> Patient.objects.filter(age__gte=39).all()  
<QuerySet [<Patient: smith, susam is 40 years old.>, <Patient: smith, adam is 40 years old.>, <Patient: marx, karl is 40 years old.>, <Patient: gou, edward is 40 years old.>]>

 

 

 

그외 exclude, order_by, reverse 같은 것도 있습니다.

 

>>> from office.models import Patient               
>>> from django.db.models import Q                                 
>>>
>>> Patient.objects.order_by('age').all()
<QuerySet [<Patient: smith, carl is 30 years old.>, <Patient: bolus, mimi is 36 years old.>, <Patient: smith, adam is 40 years old.>, <Patient: smith, susam is 42 years old.>, <Patient: marx, karl is 45 years old.>, <Patient: gou, edward is 49 years old.>]>
>>>
>>>
>>> Patient.objects.order_by('-age').all()
<QuerySet [<Patient: gou, edward is 49 years old.>, <Patient: marx, karl is 45 years old.>, <Patient: smith, susam is 42 years old.>, <Patient: smith, adam is 40 years old.>, <Patient: bolus, mimi is 36 years old.>, <Patient: smith, carl is 30 years old.>]>
>>>