Django advanced query FQ query

F object

The previous query used to compare the properties of an object with a constant value. How do the two properties compare? Answer: The use of F objects is defined in django.db.models.

The syntax is as follows:

F(属性名)
  • Example: Query books with a reading volume greater than or equal to the review volume.

    from django.db.models import F
    
    BookInfo.objects.filter(readcount__gt=F('commentcount'))
    <QuerySet [<BookInfo: 雪山飞狐>]>
    

You can use arithmetic operations on F objects.

  • Example: Query books with a reading volume greater than 2 times the number of reviews.

    BookInfo.objects.filter(readcount__gt=F('commentcount')*2)
    <QuerySet [<BookInfo: 雪山飞狐>]>
    

Q object

Multiple filters are called one by one to indicate logic and relationship, and the and keyword in the where part of the SQL statement.

  • Example: Query books with a reading volume greater than 20 and a number less than 3.

    BookInfo.objects.filter(readcount__gt=20,id__lt=3)
    <QuerySet [<BookInfo: 天龙八部>]>
    

    or

    BookInfo.objects.filter(readcount__gt=20).filter(id__lt=3)
    <QuerySet [<BookInfo: 天龙八部>]>
    

If you need to implement a logical or or query, you need to use the Q () object combined with the | operator, and the Q object is defined in django.db.models.

The syntax is as follows:

Q(属性名__运算符=)
  • Example: Query books with a reading volume greater than 20 and rewrite them as Q objects as follows.

    BookInfo.objects.filter(Q(readcount__gt=20))
    

Q objects can be connected with &, |, & represents logical AND, and | represents logical OR.

  • Example: Querying books with a reading volume greater than 20 or a number less than 3 can only be implemented using Q objects

    BookInfo.objects.filter(Q(readcount__gt=20)|Q(id__lt=3))
    <QuerySet [<BookInfo: 射雕英雄传>, <BookInfo: 天龙八部>, <BookInfo: 雪山飞狐>]>
    

Before the Q object, you can use the ~ operator to indicate non-not.

  • Example: Query books with a number not equal to 3.

    BookInfo.objects.filter(~Q(id=3))
    <QuerySet [<BookInfo: 射雕英雄传>, <BookInfo: 天龙八部>, <BookInfo: 雪山飞狐>]>
    
Published 125 original articles · Like 260 · Visits 120,000+

Guess you like

Origin blog.csdn.net/weixin_44685869/article/details/105399870