Query Extra of Django framework

extra

extra(select=None, where=None, params=None,
      tables=None, order_by=None, select_params=None)

In some cases, Django's query syntax is difficult to express complex  WHERE  clauses simply. For such cases, Django provides the  extra()  QuerySet modification mechanism — it can  inject new clauses into the SQL clauses generated by the QuerySet .

extra can specify one or more  parameters , such as  selectwhere  or  tablesNone of these parameters are required, but you must use at least one! Be aware that these extra methods may have portability problems for different database engines. (Because you In explicit writing SQL statements), unless absolutely necessary, try to avoid doing so.

parameter selection  

The  select  parameter allows you   to add other field information to the SELECT clause, it should be a dictionary that stores the mapping of attribute names to SQL clauses.

queryResult=models.Article
           .objects.extra(select={'is_recent': "create_time > '2018-04-18'"})

Each Entry object in the result set has an additional attribute is_recent, which is a boolean value indicating whether the create_time of the Article object is later than 2018-04-18.  

practise:

# in sqlite:
    article_obj=models.Article.objects
              .filter (not = 1)
              .extra(select={"standard_time":"strftime('%%Y-%%m-%%d',create_time)"})
              .values("standard_time","nid","title")
    print(article_obj)
    # <QuerySet [{'title': 'MongoDb Getting Started Tutorial', 'standard_time': '2017-09-03', 'nid': 1}]>  

Where /tables of parameters

You can use where to define an explicit SQL  WHERE clause - perhaps to perform a non-explicit join. You can manually add tables to the SQL  FROM clause using tables .

Both where and tables accept a list of strings. All where parameters are "and" with any other search criteria.

practise:

queryResult=models.Article
           .objects.extra(where=['nid in (1,3) OR title like "py%" ','nid>2'])

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324959205&siteId=291194637