dajngo ORM查询中select_related的作用,博客主题的定制,从数据库中按照年月筛选时间

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'
posted @ 2018-06-17 16:59  梦中琴歌  阅读(243)  评论(0编辑  收藏  举报