针对这俩周给爬虫搭建的Django后台,对之前不知道的只是作出小结
1.model外键的使用与查询
2.注意给所有的model加上
create_time = models.DateTimeField(auto_now_add=True)
update_time = models.DateTimeField(auto_now=True)
3.表单。在不连接数据库情况下还是自己写表单好看方便,注意type=hidden的使用,只有text,hidden类型的才能提交,提交到后台查询的key值就是input标签的name,如果有多个hidden需要提交,需要把这些值挨个遍历后提交或使用(POST.getlist())(这方式多好。。)得到全部值
4.为做到低耦合在模版中使用{%url 'url_name' 参数%}这种方式
5.数据库查询争取一次性完成
article_list = Article.objects.filter(gzh__weixin_id__exact=gzh_id)[0:]
避免遍历数据库的情况出现
6.注意views中的context的数据结构形式
ef article(request, gzh_id):
article_list = Article.objects.filter(gzh__weixin_id__exact=gzh_id)[0:]
grouped_articles = {}
for article in article_list:
articles = grouped_articles.get(article.publish_date) or []
articles.append(article)
grouped_articles[article.publish_date] = articles
sorted_articles = sorted(grouped_articles.items(), reverse=True)
# article_context = {'date_articles': sorted_articles}
paginator = Paginator(sorted_articles, 10)
page = request.GET.get('page')
try:
article_context = paginator.page(page)
except PageNotAnInteger:
article_context = paginator.page(1)
except EmptyPage:
article_context = paginator.page(paginator.num_page)
return render_to_response('article_list.html', {'date_articles': article_context})
'''
list = [
{'date': date_str1, 'articles': [article1, article2]},
{'date': date_str2, 'articles': articl_list},
{'date': date_str3, 'articles': articl_list}
]
'''
6.Django自带的分页使用起来超简单,有机会要挑战下bootstrapt_table
7.还有定时的djangocron和commands
8.model字段中使用unique的话,用get_or_cerate()填充数据要注意数据库是否定义相同字段或空字段