쿼리셋 리턴
데이타베이스의 모든 객체 다 가져옴,
여기서, filter() or exclude()로 refine 가능
Entry.objects.all().filter(pub_date__year=2006)
Entry.objects.filter(
... headline__startswith='What'
... ).exclude(
... pub_date__gte=datetime.date.today()
... ).filter(
... pub_date__gte=datetime.date(2005, 1, 30)
... )
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())
쿼리셋 메소드를 입력할 때 마다 쿼리셋이 도는것이 아니다. Evaluate될때 까지 아무것도 안한다.
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)
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.
filter() 쿼리셋 리턴한다.
만약 한개의 객체만 있더라도 가져온다.
만약 너가 only one 객체인것을 안다면 GET 메소드를 써도 된다.
one_entry = Entry.objects.get(pk=1)
filter()with slice of [0] 와 get() 다른점이 있는데,
If there are no results that match the query, GET() will raise a DoesNotExist exception.
만약 get(name='냐옹이')
했는데 2개 이상이 나오면
it will raise MultipleObjectsReturned, which again is an attribute of the model class itself.
Entry.objects.all()[:5]
Entry.objects.all()[5:10]
Entry.objects.all()[:10:2]
0 ~ 4번째
5 ~ 9번쨰
0 ~ 9번쨰 , 2개씩 건너뜀 0 ,2, 4, 6, 8 번 째만 나옴
하지만 [-1] 이렇게 마지막꺼 가져오는 파이썬 문법은 안된다.
values(별표fields, 별표별표expressions)
Returns a QuerySet that returns dictionaries, rather than model instances, when used as an iterable.
This example compares the dictionaries of values() with the normal model objects: