django学习02-模型的使用

新手做的笔记,很可能会有理解错误的地方.欢迎拍砖.
mysite/settings.py的INSTALLED_APPS选项中定义了几个默认的app,又如django.contrib.admin,django.contrib.auth...这些app要用到一些数据库表,用下面命令建表.

python manage.py migrate

想要查看建了哪些表.要先下载sqlite3的客户端,切到db.sqlite3目录下.然后执行下面命令就可以看到建了哪些表.

sqlite3.exe
.open db.sqlite3
.schema

在文件polls/models.py中建2个模型,代码如下:

from django.db import models
class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

Question的question_text表示问题的内容,pub_date表示问题的日期.Choice的question是Question的一个外键,表示Choice对应的问题.models.CASCADE表示级联,Question删除时,对应的Choice都删除.choice_text表示Choice的内容,votes表示投了几次票.
把polls加到工程中,修改mysite/settings.py

    'polls.apps.PollsConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

执行下面命令,在文件polls/migrations/0001_initial.py中生成一些操作模型的api.

python manage.py makemigrations polls

执行下面命令,生成和模型对应的一些数据库表的建表脚本.

python manage.py sqlmigrate polls 0001

再执行建表命令.

python manage.py migrate

之后可以用下面命令进入命令行,通过python api对数据库表进行增删查改.

python manage.py shell

具体方法可以看参考资料.需要注意的是执行Question.objects.all()的时候,希望输入的是问题的内容,结果输出的是表示对象的引用.想要输出内容就要重写__str__函数.

from django.db import models
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible  # only if you need to support Python 2
class Question(models.Model):
    # ...
    def __str__(self):
        return self.question_text
@python_2_unicode_compatible  # only if you need to support Python 2
class Choice(models.Model):
    # ...
    def __str__(self):
        return self.choice_text

django很牛的功能是可以直接生成管理员界面和表,执行以下命令.按提示设置用户名和密码.

python manage.py createsuperuser

启动服务器.

python manage.py runserver

再输入http://127.0.0.1:8000/admin/就能看到管理员的界面.
在polls/admin.py输入下面的代码,就能在界面上修改Question的内容.

from django.contrib import admin
from .models import Question
admin.site.register(Question)

参考资料

https://docs.djangoproject.com/en/1.11/intro/tutorial02/

原文地址:https://www.cnblogs.com/zhouyang209117/p/7221874.html