F() expression
Using F() objects can directly reference the values of model fields and perform database operations instead of importing them into python 's memory and then performing operations, which can efficiently complete batch data operations.
for example
- Without using the F() expression, if we want to increase the price of all books by 50 yuan, we can write the code like this
books = Book.objects.all() for book in books: book.price += 50 book.save()
- Use F() expression combined with update() method to modify the price of books
from django.db.models import F books = Book.objects.update(price=F('price')+50)
- Do not use F() expressions to query data information with the same value in the name field and emai field
authors = Author.objects.all() for author in authors: if author.name == author.email: print(author)
- Use the F() expression to query data information with the same value in the name field and emai field
from django.db.models import F authors = Author.objects.filter(name=F("email"))
Q() expression
The Q() expression can realize logical operations such as OR , & , NOT~ .
for example
- The query book id number is1Or title isDream of the Red ChamberBook information
from django.db.models import Q books = Book.objects.filter(Q(id=1) | Q(name='红楼梦'))
- Queries book title isThree KingdomsAnd the price is98Book information
from django.db.models import Q book = Book.objects.filter(Q(name='三国演义') & Q(price=98))
- Queries title is notThree KingdomsBook information
from django.db.models import Q books = Book.objects.filter(~Q(name='三国演义'))