1. Add data
Call this route to execute the processing method of ModelsCaozuo
The first instantiated class
class ModelsCaozuo(View): ''' Database CRUD ''' def get(self, request): item = Item() article.title = " How to add a table of data that has multiple fields " article.content = " Instantiate the model and assign values through .attr " article.message = " Use django's save to persist data " article.save() return HttpResponse("%s<br>%s<br>%s" % (article.title, article.content, article.message))
The second is not instantiated
class ModelsCaozuo1(View): ''' Database CRUD ''' def get(self, request): Article( title = " Add data without instantiating, use the class directly " , content="66666666666", message = " Also persist data through django's save " ).save() return HttpResponse("%s<br>%s<br>%s" % (Article.title, Article.content, Article.message)) # 取不到数据?
2. Query data
Query all data in the table
class ModelsCaozuo2(View): ''' Query all data in the Article table ''' def get(self, request): content_all = Article.objects.all() print content_all # QuerySet实例 列表 可 for in # <QuerySet [<Article: Article object>,
<Article: Article object>] return render(request, 'mysql_select.html', locals())
mysql_select.html page get attributes
<body> {% for con in content_all %} The data in each table corresponds to an instance con of the Article class {{ con.title }}<br> {{ con.content }}<br> {{ con.message }}<br> {% endfor %} </body>