One to Many Relationship

OR operation in ORM

Use 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
  • When querying (method)

  • Lookup

    • get()

      • Returns the object matching the given lookup parameters

      • Returns exactly one or Error occurs

      • ex) RUD (Read / Update / Delete)

    • filter()

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

        • (if none, returns empty 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

  • Django query for individual Object CRUD

  • Used when you want to see QuerySet as combined results

    • ex)

Annotate

ex) COUNT( )

  • Manipulate necessary values from results fetched from DB

1:N (one to many)

  • 1 has many N

  • N must belong to 1

    • (Therefore cascading is possible)

    • ex)

      • Article has many Comments

    • Comment belongs to Article

  • Foreign Key is given to N

  • A reporter_id column is added to the articles_article table.

  • In the case of reporter, you can fetch N items (QuerySet) with article_set.

  • In the case of article, you can fetch 1 corresponding object with reporter.

  • on_delete : When the referenced target is deleted

    • CASCADE

      • When the corresponding object(reporter) is deleted, all referencing objects(article) are also deleted

    • PROTECT

      • Deletion is prohibited if referencing objects(article) exist

    • SET_NULL

      • Replace with NULL value

      • Cannot be used if NOT NULL option exists

    • SET_DEFAULT

      • Reference the default value(article)

Basic Queries

1. Preparation

2. Create article (N)

3. Using 1:N Relationship

  • article_set

Comment exercise

Important Note

  • It must be article_id

    • Aliases cannot be used!

  • To avoid calling with the default related_name .comment_set, modify models.py

    • Set related_name= 'comments'

      • However, since this is just changing an option, migration is not needed!

  • After modification, can be called with 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

For reference

Update, delete can be applied to individual objects and querysets

Exercises

Preparation

Create onetomany app

Problems

  1. Articles written by user #1

  2. Print all content of comments written by user #2

  3. Print all content of comments written on article #3

  4. Posts with title "1글"

  5. Posts containing the word "글"

  6. Comments(N) where the corresponding article(1) title is "1글"

    • Filtering by 1's column in 1:N relationship

+

Open sqlite with Django handling

Option to directly show ORM query in Shell

Last updated