Making queries

dooh kim·2020년 4월 25일
0

Making queries

Once you’ve created your data models, Django automatically gives you a database-abstraction API that lets you create, retrieve, update and delete objects. This document explains how to use this API. Refer to the data model reference for full details of all the various model lookup options.

data model을 만들면 django는 자동적으로 database에서 사용하는 sql문으로 바꿔서 database table을 create, retrieve, update, delete하는 objects로 사용하는 API를 제공한다. 이 문서는 API를 사용하는 방법을 설명하고 data model에 대한 다양한 옵션들을 데이터 모델 참조 문서에서 확인하세요

Throughout this guide (and in the reference), we’ll refer to the following models, which comprise a Weblog application:

이 가이드 문서는 다음 밑에 모델을 참조할거야

django-admin startproject config
mv config app
cd app
./manage.py startapp blog

Installed_app = blog.apps.BlogConfig 추가하세요

추가적인 부분

auto_now_add (인스턴스 생성시 자동으로 추가)
auto_now (인스턴스 update할 때 수정됨)

blog/models.py

from django.db import models


class Blog(models.Model):
    name = models.CharField(max_length=100)
    tagline = models.TextField()

    def __str__(self):
        return self.name


class Author(models.Model):
    name = models.CharField(max_length=200)
    email = models.EmailField()

    def __str__(self):
        return self.name


class Entry(models.Model):
    blog = models.ForeignKey(Blog, on_delete=models.CASCADE)
    headline = models.CharField(max_length=255)
    body_text = models.TextField()
    pub_date = models.DateField(auto_now_add=True)
    mod_date = models.DateField(auto_now=True)
    authors = models.ManyToManyField(Author)
    number_of_comments = models.IntegerField()
    number_of_pingbacks = models.IntegerField()
    rating = models.IntegerField()

    def __str__(self):
        return self.headline

Creating objects

To represent database-table data in Python objects, Django uses an intuitive system: A model class represents a database table, and an instance of that class represents a particular record in the database table.

To create an object, instantiate it using keyword arguments to the model class, then call save() to save it to the database.

python objects로 database-table을 표현하기 위해 직관적으로 사용한다.
models class name == table name
instance.save == record

Assuming models live in a file config/blog/models.py, here’s an example:

pip install notebook django-extensions
installed_app = django_extensions 추가
./manage.py shell_plus 사용하자

from blog.models import Blog
b = Blog(name='Beatles Blog', tagline='All the latest Beatles news.')
b.save()

This performs an INSERT SQL statement behind the scenes. Django doesn’t hit the database until you explicitly call save().

The save() method has no return value.

See also

save( ) takes a number of advanced options not described here. See the documentation for save() for complete details.
To create and save an object in a single step, use the create() method.

save() 함수 호출은 INSERT SQL 과 같다 save() or create()
를 하기 전까지 database에 hit(저장)되지 않는다


blog2, _ = Blog.objects.get_or_create(name='dooh', tagline='let us start')


joe,_ = Author.objects.get_or_create(name='joe')
paul,_ = Author.objects.get_or_create(name='Paul')

john,_ = Author.objects.get_or_create(name="John")
george,_ = Author.objects.get_or_create(name="George")
ringo,_ = Author.objects.get_or_create(name="Ringo")


entry = Entry(
    blog=blog, 
    headline='가짜뉴스',
    body_text = '가짜뉴스 검증을 위한 프로젝트를 만들까하는데 내가 할수 있을거야',
    number_of_comments = '2',
    number_of_pingbacks = '3',
    rating = '13',

)

# manytomany 제외하고 저장됨 데이터베이스에 
# m2m은 직접적으로 할당이 안됨
entry.save()

entry.authors.add(paul,joe, john, george, ringo)

Retrieving objects

To retrieve objects from your database, construct a QuerySet via a Manager on your model class.

A QuerySet represents a collection of objects from your database. It can have zero, one or many filters. Filters narrow down the query results based on the given parameters. In SQL terms, a QuerySet equates to a SELECT statement, and a filter is a limiting clause such as WHERE or LIMIT.

You get a QuerySet by using your model’s Manager. Each model has at least one Manager, and it’s called objects by default. Access it directly via the model class, like so:

DB에서 객체를 검색하기 위해서 query set 사용한다 model class에 Manager 객체를

QuerySet을 통해 zero, one 혹은 많은 데이터를 가질 수 있다.
Filter는 query 파라미터를 제공함으로써 결과를 줄여준다.(WHERE or LIMIT)
models. Manager는 적어도 하나의 Manager를 가지고 QuerySet을 얻는다.

>>> Blog.objects
<django.db.models.manager.Manager object at ...>
>>> b = Blog(name='Foo', tagline='Bar')
>>> b.objects
Traceback:
    ...
AttributeError: "Manager isn't accessible via Blog instances."

Note
Managers are accessible only via model classes, rather than from model instances, to enforce a separation between “table-level” operations and “record-level” operations.
model 인스턴스에서 model class에 접근할 수 없다 오직 Manager에서만 접근 가능하고

Table-level == models.Manager (ex. Author.objects.create)
record-level == blog.author (ex. Entry.objects.first().filter(blog_id=4)

The Manager is the main source of QuerySets for a model. For example, Blog.objects.all() returns a QuerySet that contains all Blog objects in the database.

Manager 는 Queryset 의 주 재료이다. for a model
Blog.objects.all() 데이터 베이스에서 모든 Blog 객체들을 포함시킨 QuerySet을 반환한다.

Retrieving all objects

The simplest way to retrieve objects from a table is to get all of them. To do this, use the all() method on a Manager:

>>> all_entries = Entry.objects.all()

The all() method returns a QuerySet of all the objects in the database.

모든 것을 가져오기 위해 table에서 객체들을 조회하는 가장 간단한 방법이다 위에 코드는

Retrieving specific objects with filters

The QuerySet returned by all() describes all objects in the database table. Usually, though, you’ll need to select only a subset of the complete set of objects.

To create such a subset, you refine the initial QuerySet, adding filter conditions. The two most common ways to refine a QuerySet are:

filter(**kwargs)

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

exclude(**kwargs)

Returns a new QuerySet containing objects that do not match the given lookup parameters.
The lookup parameters (**kwargs in the above function definitions) should be in the format described in Field lookups below.

데이터 베이스에서 모든 객체를 가져온다. 그러나 보통 부분 객체(하위)를 조회가 필요할 것이다.
너는 초기 QuerySet을 재정의 한다 filter 조건을 이용해서

filter(**kwargs) 주어진 lookup 파라미터와 매칭되는 것을 포함한 새로운 QuerySet을 반환한다

exclude(**kwargs) 주어진 파라미터와 매칭된 것 이외에 데이터들의 객체들을 포함한 QuerySet을 반환한다.

For example, to get a QuerySet of blog entries from the year 2006, use filter() like so:

Entry.objects.filter(pub_date__year=2006)
With the default manager class, it is the same as:

Entry.objects.all().filter(pub_date__year=2006)
Chaining filters¶
The result of refining a QuerySet is itself a QuerySet, so it’s possible to chain refinements together. For example:

<django.db.models.manager.Manager object at ...>

>>> Entry.objects.filter(
...     headline__startswith='What'
... ).exclude(
...     pub_date__gte=datetime.date.today()
... ).filter(
...     pub_date__gte=datetime.date(2005, 1, 30)
... )

This takes the initial QuerySet of all entries in the database, adds a filter, then an exclusion, then another filter. The final result is a QuerySet containing all entries with a headline that starts with “What”, that were published between January 30, 2005, and the current day.

Filtered QuerySets are unique¶
Each time you refine a QuerySet, you get a brand-new QuerySet that is in no way bound to the previous QuerySet. Each refinement creates a separate and distinct QuerySet that can be stored, used and reused.

Example:

<django.db.models.manager.Manager object at ...>
>>> q1 = Entry.objects.filter(headline__startswith="What")
>>> q2 = q1.exclude(pub_date__gte=datetime.date.today())
>>> q3 = q1.filter(pub_date__gte=datetime.date.today())

These three QuerySets are separate. The first is a base QuerySet containing all entries that contain a headline starting with “What”. The second is a subset of the first, with an additional criteria that excludes records whose pub_date is today or in the future. The third is a subset of the first, with an additional criteria that selects only the records whose pub_date is today or in the future. The initial QuerySet (q1) is unaffected by the refinement process.

QuerySets are lazy¶

QuerySets are lazy – the act of creating a QuerySet doesn’t involve any database activity. You can stack filters together all day long, and Django won’t actually run the query until the QuerySet is evaluated. Take a look at this example:

<django.db.models.manager.Manager object at ...>

>>> q = Entry.objects.filter(headline__startswith="What")
>>> q = q.filter(pub_date__lte=datetime.date.today())
>>> q = q.exclude(body_text__icontains="food")
>>> print(q)

Though this looks like three database hits, in fact it hits the database only once, at the last line (print(q)). In general, the results of a QuerySet aren’t fetched from the database until you “ask” for them. When you do, the QuerySet is evaluated by accessing the database. For more details on exactly when evaluation takes place, see When QuerySets are evaluated.

Retrieving a single object with get()¶

filter() will always give you a QuerySet, even if only a single object matches the query - in this case, it will be a QuerySet containing a single element.

If you know there is only one object that matches your query, you can use the get() method on a Manager which returns the object directly:

<django.db.models.manager.Manager object at ...>

>>> one_entry = Entry.objects.get(pk=1)
You can use any query expression with get(), just like with filter() - again, see Field lookups below.

Note that there is a difference between using get(), and using filter() with a slice of [0]. If there are no results that match the query, get() will raise a DoesNotExist exception. This exception is an attribute of the model class that the query is being performed on - so in the code above, if there is no Entry object with a primary key of 1, Django will raise Entry.DoesNotExist.

Similarly, Django will complain if more than one item matches the get() query. In this case, it will raise MultipleObjectsReturned, which again is an attribute of the model class itself.

Other QuerySet methods¶

Most of the time you’ll use all(), get(), filter() and exclude() when you need to look up objects from the database. However, that’s far from all there is; see the QuerySet API Reference for a complete list of all the various QuerySet methods.

profile
testify to the light

0개의 댓글