One to Many Relationship

ORM에서의 or 연산

Q를 활용한다

In [1]: from django.db.models import Q                  

In [2]: User.objects.filter(Q(age=30) | Q(last_name='김'
   ...: )).count()                                      
Out[2]: 25

QuerySet

In [4]: User.objects.all()                              
Out[4]: <QuerySet [<User: User object (1)>, <User: User object (2)>, <User: User object (3)>, <User: User object (4)>, <User: User object (5)>, <User: User object (6)>, <User: User object (7)>, <User: User object (8)>, <User: User object (9)>, <User: User object (10)>, <User: User object (11)>, <User: User object (12)>, <User: User object (13)>, <User: User object (14)>, <User: User object (15)>, <User: User object (16)>, <User: User object (17)>, <User: User object (18)>, <User: User object (19)>, <User: User object (20)>, '...(remaining elements truncated)...']>

In [5]: type(User.objects.all())                        
Out[5]: django.db.models.query.QuerySet
  • Query (method) 할 때

  • 조회 (loop up)

    • get()

      • Returns the object matching the given lookup parameters

      • return오직 하나 or Error 발생

      • ex) RUD (Read / Update / Delete)

    • filter()

      • Returns a new QuerySet containing objects that match the given lookup parameters.

        • (없으면 비어있는 QuerySet)

      • ex) Search

      • AND

        • method chaining

        • filter. filter. ....

      • OR

        • Q Object

        • (Q ( ) | Q ( ) )

      • LIKE

        • ex) age__lte

        • ex) name__startswith

    • exclude()

      • Returns a new QuerySet containing objects that do not match the given lookup parameters.

ex)

Aggregation

  • 개별 Object CRUD를 django query

  • QuerySet을 합쳐진 결과로 보고싶을 때 사용

    • ex)

Annotate

ex) COUNT( )

  • DB에서 가져온 결과에서 필요한 값을 조작하여 가져옴

1:N (one to many)

  • 1 has many N

  • N must belong to 1

    • (그래서 cascading이 가능하다)

    • ex)

      • Article has many Comments

    • Comment belongs to Article

  • Foreign KeyN 에게 준다

  • articles_article table에 reporter_id column이 추가된다

  • reporter의 경우 article_set으로 N개 (QuerySet)를 가져올 수 있다.

  • article의 경우 reporter`로 1에 해당하는 object를 가져올 수 있다

  • on_delete : 참조 대상이 삭제되는 경우

    • CASCADE

      • 해당 객체(reporter)가 삭제 되었을 때 참조하는 객체도(article) 모두 삭제

    • PROTECT

      • 참조하는 객체(article)가 존재하면 삭제 금지

    • SET_NULL

      • NULL 값으로 치환

      • NOT NULL option이 있는 경우 활용 할 수 없음

    • SET_DEFAULT

      • default값(article)을 참조하게 함

기본 쿼리

1. 준비

2. article 생성 (N)

3. 1:N 관계 활용

  • article_set

Comment exercise

주의 할 점

  • 무조건 article_id이다

    • 별명 사용 불가!

  • default related_name.comment_set으로 호출하지 않기 위해 models.py 수정

    • related_name= 'comments' 로 설정함

      • 단, 여기서는 option을 바꾼 것 이므로 migration 안해도 됨!

  • 수정 후 comments로 호출 가능해짐

Data Seeding

CSV -> DB

Data Integrity

  • the maintenance of, and the assurance of the accuracy and consistency of data over its entire life-cycle

  • a critical aspect to the design, implementation and usage of any system which stores, processes, or retrieves data

Entity Integrity

  • defines each row to be unique within its table.

    • No two rows can be the same.

  • To achieve this, a primary key can be defined.

    • The primary key field contains a unique identifier – no two rows can contain the same unique identifier.

Referential Integrity

  • concerned with relationships.

    • When two or more tables have a relationship, we have to ensure that the foreign key value matches the primary key value at all times.

    • We don’t want to have a situation where a foreign key value has no matching primary key value in the primary table.

    • This would result in an orphaned record.

So referential integrity will prevent users from:

  • Adding records to a related table if there is no associated record in the primary table.

  • Changing values in a primary table that result in orphaned records in a related table.

  • Deleting records from a primary table if there are matching related records.

Domain Integrity

  • concerns the validity of entries for a given column.

  • Selecting the appropriate data type for a column is the first step in maintaining domain integrity.

  • Other steps could include, setting up appropriate constraints and rules to define the data format and/or restricting the range of possible values.

User-Defined Integrity

  • allows the user to apply business rules to the database that aren’t covered by any of the other three data integrity types.

Django settings.py

https://github.com/django/django/blob/master/django/conf/global_settings.pyarrow-up-right

참고하기

Update, delete는 개별 객체와 쿼리셋에 적용가능

Excercises

준비

onetomany app 생성

문제

  1. 1번 유저가 작성한 글들

  2. 2번 유저가 작성한 댓글의 내용을 모두 출력

  3. 3번 글의 작성된 댓글의 내용을 모두 출력

  4. 1글이라는 제목인 게시글들

  5. 글이라는 단어가 들어간 게시글들

  6. 댓글(N)들 중에 해당되는 글(1)의 제목이 1글인 것

    • 1:N 관계에서 1의 열에 따라서, 필터링

+

Django 에게 맡겨서 sqlite 열기

Shell 에서 ORM query 바로 보여주는 option

Last updated