• Python学习笔记(Django篇)——3、创建第一个数据库模型


    Django里面集成了SQLite的数据库,对于初期研究来说,可以用这个学习。

     
    第一步,创建数据库就涉及到建表等一系列的工作,在此之前,要先在cmd执行一个命令:
    1. python manage.py migrate
    这个命令就看成一个打包安装的命令,它会根据mysite/settings.py的配置安装一系列必要的数据库表
     
    第二步,我们要建立一个Model层,修改demo/model.py:
    1. from django.db import models
    2. classQuestion(models.Model):
    3. question_text = models.CharField(max_length=200)
    4. pub_date = models.DateTimeField('date published')
    5. classChoice(models.Model):
    6. question = models.ForeignKey(Question, on_delete=models.CASCADE)
    7. choice_text = models.CharField(max_length=200)
    8. votes = models.IntegerField(default=0)
    这个Model的内容包括创建表(对象)、确定变量(字段)的类型,以及外键方面的信息
     
    第三步,要激活Model,那么现在helloworld/setting.py中修改:
    1. INSTALLED_APPS =[
    2. 'demo.apps.DemoConfig',
    3. 'django.contrib.admin',
    4. 'django.contrib.auth',
    5. 'django.contrib.contenttypes',
    6. 'django.contrib.sessions',
    7. 'django.contrib.messages',
    8. 'django.contrib.staticfiles',
    9. ]
    主要是加了第一行的内容,这个在demo/apps下有的。目的是让Django知道有demo这个app。
     
    然后就在cmd下面运行:
    1. python manage.py makemigrations demo
    可以看到在demo/migrations/0001_initial.py下面生成了很多代码
    继续run这段代码,就完成了建表工作:
    1. python manage.py sqlmigrate demo 0001
    再跑一下migrate命令,把这些model创建到数据库表中
    1. python manage.py migrate
     
    第四步,也是比较好玩的了,就是要进入到python django的shell中,执行这个命令:
    1. python manage.py shell
     在这个里面,就可以通过命令行操作数据库了
     
    先引入刚才创建好的model:
    1. from demo.models importQuestion,Choice
    这个命令,打印出Question所有的对象:
    1. Question.objects.all()
    然后创建一个Question的对象(或数据):
    1. from django.utils import timezone
    2. q =Question(question_text="What's new?", pub_date=timezone.now())
    3. q.save()
    4. q.id
    5. q.question_text
    6. q.pub_date
    7. q.question_text = "What's up?"
    8. q.save()
    9. Question.objects.all()
     
    第五步,然后polls/models.py中添加以下代码:
    1. from django.db import models
    2. from django.utils.encoding import python_2_unicode_compatible
    3. @python_2_unicode_compatible# only if you need to support Python 2
    4. classQuestion(models.Model):
    5. # ...
    6. def __str__(self):
    7. return self.question_text
    8. @python_2_unicode_compatible# only if you need to support Python 2
    9. classChoice(models.Model):
    10. # ...
    11. def __str__(self):
    12. return self.choice_text
    1. import datetime
    2. from django.db import models
    3. from django.utils import timezone
    4. classQuestion(models.Model):
    5. # ...
    6. def was_published_recently(self):
    7. return self.pub_date >= timezone.now()- datetime.timedelta(days=1)
    在这里__str__()是一个非常重要的方法,大概可以看成java里pojo对象的一个toString()方法
    接下来,就可以在数据库中进行很多操作,在shell中输入以下的代码,就可以执行对数据库的增删查改:
    1. from polls.models importQuestion,Choice
    2. Question.objects.all()
    3. Question.objects.filter(id=1)
    4. Question.objects.filter(question_text__startswith='What')
    5. from django.utils import timezone
    6. current_year = timezone.now().year
    7. Question.objects.get(pub_date__year=current_year)
    8. Question.objects.get(id=2)
    9. Question.objects.get(pk=1)
    10. q =Question.objects.get(pk=1)
    11. q.was_published_recently()
    12. q =Question.objects.get(pk=1)
    13. q.choice_set.all()
    14. q.choice_set.create(choice_text='Not much', votes=0)
    15. q.choice_set.create(choice_text='The sky', votes=0)
    16. c = q.choice_set.create(choice_text='Just hacking again', votes=0)
    17. c.question
    18. q.choice_set.all()
    19. q.choice_set.count()
    20. Choice.objects.filter(question__pub_date__year=current_year)
    21. c = q.choice_set.filter(choice_text__startswith='Just hacking')
    22. c.delete()
     
     
     
     
     
    操作django Admin
     
     
    Django的管理端可以管理站点、管理账户权限等等。
    在cmd运行以下的脚本创建账户:
    1. python manage.py createsuperuser
    2. Username: admin
    3. Email address: admin@example.com
    4. Password:**********
    5. Password(again):*********
    6. Superuser created successfully.
    启动server:
    1. python manage.py runserver 8081
    访问链接地址:
     
    登录界面:
     管理界面:
     在demo/admin.py中添加代码注册对象:
    1. from django.contrib import admin
    2. from.models importQuestion
    3. admin.site.register(Question)
     
    刷新后即增加这个对象:
     点击Questions进去:
     这样,就可以在图形化的界面中执行增删查改了。
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
  • 相关阅读:
    IoC就是IoC,不是什么技术,与GoF一样,是一种 设计模式。
    控制反转是Spring框架的核心。
    一种是CI(Constructor Injection)构造方法注入,另一种是SI(Set Injection) set 注入
    IOC 的理解与解释
    java 单例模式5种写法
    AOP(Aspect Oriented Programming),即面向切面编程
    AOP称为面向切面编程,在程序开发中主要用来解决一些系统层面上的问题
    ioc和aop的区别?
    JAVA设计模式之单例模式
    详解JNDI的lookup资源引用 java:/comp/env
  • 原文地址:https://www.cnblogs.com/leejy/p/6745186.html
Copyright © 2020-2023  润新知