Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ Retrieve Query | Queries
/
Django ORM Ninja: Advanced Techniques for Developers

bookRetrieve Query

メニューを表示するにはスワイプしてください

We already know how to retrieve all instances using Author.objects.all(). In this chapter, we'll learn how to obtain a specific instance or filter multiple instances based on certain attributes.

filter()

Author.objects.filter(last_name="Clear")

This query returns a new QuerySet containing objects that match the given lookup parameters. In our example, it will return only one Author with id=3.

The equivalent SQL command is SELECT * FROM Author WHERE last_name = 'Clear';

exclude()

Author.objects.exclude(last_name="Clear")

Conversely, exclude() returns a QuerySet with objects that do not match the specified parameters. Here, it will include all Authors whose last name isn't "Clear".

The equivalent SQL command is SELECT * FROM author WHERE last_name != 'Clear';

Combine filters

Author.objects.filter(last_name__startswith="C").exclude(first_name="Ronald") 

We can also combine filters. For instance, the query above demonstrates how to use multiple lookups, which we will explore more in the next sections.

The equivalent SQL command is SELECT * FROM author WHERE last_name LIKE 'C%' AND first_name != 'Ronald';

get()

Author.objects.get(pk=1)

To retrieve a specific object, we use the get method, where pk is a "primary key", and it's the same as id.

The equivalent SQL command is SELECT * FROM author WHERE id = 1;

Unlike get(), slicing with filter() doesn't raise an exception if there are no matching results; it simply returns an empty QuerySet.

1. What does Author.objects.filter(last_name="Clear") return in Django?

2. How does the exclude() method in Django differ from filter()?

3. Which query combines multiple filters in Django?

4. What does the get() method do in Django?

5. How does Django's filter() method behave when there are no matching results?

question mark

What does Author.objects.filter(last_name="Clear") return in Django?

正しい答えを選んでください

question mark

How does the exclude() method in Django differ from filter()?

正しい答えを選んでください

question mark

Which query combines multiple filters in Django?

すべての正しい答えを選択

question mark

What does the get() method do in Django?

正しい答えを選んでください

question mark

How does Django's filter() method behave when there are no matching results?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 3.  2

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 3.  2
some-alt