Article From:



FQuery: a comparison between 2 fields

from django.db.models import F


You can also perform operations behind F (), but only for digits.



What if a string is modified?

There are 2 ways to use:

from django.db.models.functions import Concat

from django.db.models import Value

models.Book.objects.all().update(title=Concat(F(‘title’),Value(”(”),Value(‘First ‘), (‘ ‘),’ ‘)))



Perform more complex statements, such as OR,

models.Book.objects.filter(Q(author__name=’The little fairy ‘) |Q (author__name=’ little girl “)

You can write arbitrary complex Q objects by grouping AND and operator and parentheses. You can also use Q to reverse operation.

For example, the name of the author is the fairy and not the title of the book that was published in 2018.

models.Book.objects.filter(Q(author__name=’Fairies’ & ~Q (publish_date__year=2018).Values_list (‘title’))


Queries can be mixed with Q objects and keyword parameters, separated by commas, and intersected, but Q objects should be in front of keyword parameters.!!!!!

The year of enquiry and publication is 2018 or 2017.

models.Book.objects.filter(Q(publish_date__year=2018) | Q(pulisher_date__year=2017),title__contains=’Language “)


Transaction: a concept with database transaction, the value changes together, and one side fails, and the data remains unchanged.

The fixed format is as follows:


  from django.db import transaction

  with transaction.atomic():

    new_publisher=models.Publisher.objects.create(name=’Mars press

    models.Book.objects.create(title=’Orange story, ()


except Exception as e:



updateQueryset object operation, save is the operation of objects.

updateIt is to update a certain field with higher efficiency. Save is updating all fields with low efficiency.



  1.select_related And prefetch_related

    1.select_related Reducing the number of query databases using the JOIN of SQL

    2.prefetch_related Using Python to do similar JOIN operations


3.ORMThe method of executing native SQL:

  1. extra

    Query the name of the book and the time of publication (year and month)


    Archiving books by year and month

    from django.db.models import Count



  2.Similar to pymysql mode

    from django.db import connection

    cursor=connection.cursor()   ## cursor = connections[‘default’].cursor()

    cursor.execute(“”” SELECT * from app01_book where id=%s”””,[1])





Link of this Article: Django ORM final operation

Leave a Reply

Your email address will not be published. Required fields are marked *