Django笔记二 使用初步

来源:互联网 发布:苏州纽奥德软件靠谱吗 编辑:程序博客网 时间:2024/06/05 14:16

一,Django ORM 

     建立一个简单博客,定义了topical和article 两个类,两个类都从models.MOdel 继承  变量类型都由models中定义,还可以设置外键,等关系。具体一对多,多对多是怎么实现稍后再详细研究。

from django.db import models# Create your models here.class Topical(models.Model):    name=models.CharField(max_length=30)    def __str__(self):        return self.nameclass Article(models.Model):    topical=models.ForeignKey(Topical)    title=models.CharField(max_length=200)    content=models.TextField()    pub_date=models.DateTimeField('date published')    def __str__(self):        return self.title
切换到应用目录下执行python manage,py makemigrate blog  (the name of app)  官方文档说这是在告诉django 你已经对model做了修改,

python manage.py migrate
是在执行上面的更改,所以每次对models.py 文件的修改都要执行以上两个命令,英文文档是这样总结的。三个步骤。

Migrations are very powerful and let you change your models over time, as you develop your project, without the need to delete your database or tables and make new ones - it specializes in upgrading your database live, without losing data. We’ll cover them in more depth in a later part of the tutorial, but for now, remember the three-step guide to making model changes:

  • Change your models (in models.py).
  • Run python manage.py makemigrations to create migrations for those changes
  • Run python manage.py migrate to apply those changes to the database.
使用manage.py shell .可以对数据库中的model进行一些操作

Article.objects.all() 查询所有的article

不像java,这里的model没有定义构造函数,跟hibernate一样简单的操作不需要sql,直接就能搞定。但是能不能,怎么执行sql,还是个问题?


二,建立admin来管理 

django 提供了一个方便的后台,

只要执行 python manage,py createsuperuser  就能设置用户名,密码等一些信息。在地址栏输入http://localhost:8000/blog/ 就能进入登录界面,输入账号密码,就能登录,来管理刚刚建立的在数据库中的model.  支持 修改成各种格式。


0 0
原创粉丝点击