Django ORM Model's basic query operation API

1. Create a Model instance object
Please refer to the data table structure of this article before reading the text
Use the save method to create a Model instance:
Since the Topic needs a User object, first obtain the User object whose username is admin (super user), and then create the Topic object
user = User.objects.get(username='admin')
topic = Topic(title='Great China', content='Long live the motherland!', user=user)
topic. save()
2. The query method that returns a single instance
Use get query:
topic = Topic.objects.get(id=1, title=u'Great China')
return HttpResponse("Hello World!" + topic. content)
Use get_or_create query:
If the queried instance does not exist, the get_or_create method will create a new instance object
The difference with get is that it returns a tuple object, namely (object,created). The first element is an instance object, and the second element is a Boolean value, identifying whether the returned instance object is newly created
3. Return the query method of QuerySet
When you need to return multiple data records, you need to use the QuerySet object
A very important feature of QuerySet is lazy loading, that is, it will only access the database to retrieve records when it is actually used
Use the all method to get all data records:
all_topic = Topic.objects.all()
return HttpResponse("Hello World!" + all_topic[0].content)
Use the order_by method to customize the collation:
Multiple sorting fields can be specified in order_by. For example, all Topic objects are first sorted in reverse order by title, and then sorted by created_time in positive order:
all_topic = Topic.objects.order_by('-title', 'created_time')
Use the filter method to filter data records:
Before using the filter method, let's take a look at the conditional query keywords:
For the keywords contains, startswith, and endswith, there are also corresponding query versions that ignore case. You only need to add the letter i before the keyword, such as icontains🛺
Query topic collection with id=1:
all_topic = Topic.objects.filter(id__exact=1)
Chain query:
Since the results returned by methods such as filter and exclude are QuerySet, methods such as filter and exclude can be called after them, thus forming a chain query
Query all active admin users:
admin_user = User.objects.filter(is_active__exact=1).
return HttpResponse("Hello World!" + admin_user[0].username)
Use the values method to get the dictionary result:
Parameters can be passed to the values method to limit the query range of SELECT
The following returns only the results of the id and title columns:
topic = Topic.objects.values('id', 'title')
return HttpResponse("Hello World!" + topic[0]['title'])
4. Return the query method of RawQuerySet
Manager provides a raw method that allows the use of native SQL statements to query the Model
topic = Topic.objects.raw('SELECT id, content FROM post_topic WHERE title = %s', ['Great China'])
return HttpResponse("Hello World!" + topic[0].content)
5. Return other types of query methods
Returns the number of objects in the QuerySet:
topic_count = Topic.objects.filter(id__gt=1).count()
return HttpResponse("Hello World!" + str(topic_count))
Determine whether the QuerySet contains objects:
Use the update method to update the Model instance:
Use the delete method to delete the Model instance:
6. Queries with related relationships
Cross-relationship query: 🧨
User may be considered when querying Topic. This is a very common scenario, also known as cross-association query.
For example: in querying the user associated with topic, the username contains the topic collection of min:
topic = Topic.objects.filter(user__username__contains='min')
This query has no depth limit:
For example: In the topic associated with the query, the collection of usernames equal to admin in the users associated with the topic:
Model's reverse query: 🛺
Every relationship in Django can implement reverse query
For example: to query the topic information associated with the user object with id=1:
user = User.objects.get(id=1)
topic = user.topic_set.all()
Similar reverse queries can also be implemented for ManyToManyField and OneToOneField relationship types, but the reverse query for OneToOneField type is special. Its manager represents a single object, not a collection of objects, and the name becomes a lowercase Model name
For example, the previously defined CustomUser has a OneToOneField relationship between its user field and Django's User. Then, User can implement reverse query like this:

Related Articles

Explore More Special Offers

  1. Short Message Service(SMS) & Mail Service

    50,000 email package starts as low as USD 1.99, 120 short messages start at only USD 1.00

phone Contact Us