1. 程式人生 > >dajngo ORM查詢中select_related的作用,博客主題的定制,從數據庫中按照年月篩選時間

dajngo ORM查詢中select_related的作用,博客主題的定制,從數據庫中按照年月篩選時間

group art posit global ont create 通過 nts object

1、dajngo ORM查詢中select_related的作用

select_related()方法一次性的把數據庫關聯的對象都查詢出來放入對象中,再次查詢時就不需要再連接數據庫,節省了後面查詢數據庫的次數和時間。主要用於外鍵查詢。

	blogobj = Blog.objects.filter(site=site).select_related(‘user‘).first()

2、博客主題的定制

將各個模塊的css樣式固定,然後通過.css文件導入,可以在數據裏面設置.css文件的名字在模板中通過 link rel="stylesheet" href="/static/css/{{blogobj.theme}}.css"

3、從數據庫中按照年月篩選時間,及數量(這裏踩過一個坑!汗!)

使用原生sql語句

首先在使用mysql語句的時候不能使用 GROUP BY 的解決方法(sqlite不存在此問題)
	Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column ‘userinfo.:解決辦法:
	mysql> set global sql_mode=‘STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION‘;
	mysql> set session sql_mode=‘STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION‘;
	第二:在mysql中時間格式化函數為date_format(ctime,"%%Y-%%m")這裏兩個%
	是為了避免django出現字符串參數確實報錯,如果不加%會報錯:
	 return "<%s: %s>" % (self.__class__.__name__, self.query)
  File "C:\Python36\lib\site-packages\django\db\models\sql\query.py",   line 110, in __str__
    return self.sql % self.params_type(self.params)
    TypeError: not enough arguments for format string
    第三使用原生語句:
    select nid ,count(nid) as num, date_format(ctime,"%Y-%m") as create_time from repository_article group by date_format(ctime,"%%Y-%%m");
    使用sqlite的寫法是:
    ‘select nid, count(nid) as num,strftime("%Y-%m",create_time) as ctime from repository_article group by strftime("%Y-%m",create_time)‘)

   這裏date_format(ctime,"%Y-%m") as create_time千萬不能寫成date_format(ctime,"%Y-%m") as ctime:因為本身ctime就是一個模塊,這裏如果寫成ctime,最後查詢的時候會報錯:
     File "C:\Python36\lib\site-packages\pytz\__init__.py", line 222, in localize
    if dt.tzinfo is not None:
    AttributeError: ‘str‘ object has no attribute ‘tzinfo‘

dajngo ORM查詢中select_related的作用,博客主題的定制,從數據庫中按照年月篩選時間