H5W3
当前位置:H5W3 > python > 正文

【Python】Django 框架中模型的使用

创建模型

polls/models.py
from django.db import models
class Question(models.Model):
question_text = models.CharField(u'问题内容', max_length=200, null=False, default='')
pub_date = models.DateTimeField(u'时间')
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE, verbose_name="问题ID")
choice_text = models.CharField(u'选项内容', max_length=200, null=False, default='')
votes = models.PositiveIntegerField(u'投票数量', null=False, default=0)

激活模型

在项目配置文件中添加应用:

# mysite/settings.py
INSTALLED_APPS = [
'polls.apps.PollsConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]

生成迁移文件:

> py manage.py makemigrations polls

查看迁移文件的内容:

> py manage.py sqlmigrate polls 0001

运行迁移:

> py manage.py migrate

测试模型 API

> py manage.py shell
>>> from polls.models import Choice, Question
>>> Question.objects.all()
<QuerySet []>
>>> from django.utils import timezone
>>> q = Question(question_text="What's new?", pub_date=timezone.now())
>>> q.save()
>>> q.id
1
>>> q.question_text
"What's new?"
>>> q.pub_date
datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=<UTC>)
>>> q.question_text = "What's up?"
>>> q.save()
>>> Question.objects.all()
<QuerySet [<Question: Question object (1)>]>

编辑 Question 模型的代码改变对象的输出内容:

# polls/models.py
import datetime
from django.db import models
from django.utils import timezone
class Question(models.Model):
# ...
def __str__(self):
return self.question_text
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
class Choice(models.Model):
# ...
def __str__(self):
return self.choice_text

重新打开交互式命令行:

> py manage.py shell
>>> from polls.models import Choice, Question
>>> Question.objects.all()
<QuerySet [<Question: What's up?>]>
>>> Question.objects.filter(id=1)
<QuerySet [<Question: What's up?>]>
>>> Question.objects.filter(question_text__startswith='What')
<QuerySet [<Question: What's up?>]>
>>> from django.utils import timezone
>>> current_year = timezone.now().year
>>> Question.objects.get(pub_date__year=current_year)
<Question: What's up?>
# 查询不存在的ID会抛出异常
>>> Question.objects.get(id=2)
DoesNotExist: Question matching query does not exist.
# 通过主键查询
>>> q = Question.objects.get(pk=1)
>>> q.was_published_recently()
True
# 关联查询问题的选项
>>> q.choice_set.all()
<QuerySet []>
# 创建选项数据
>>> q.choice_set.create(choice_text='Not much', votes=0)
<Choice: Not much>
>>> q.choice_set.create(choice_text='The sky', votes=0)
<Choice: The sky>
>>> c = q.choice_set.create(choice_text='Just hacking again', votes=0)
>>> c.question
<Question: What's up?>
# 关联查询问题的选项
>>> q.choice_set.all()
<QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>
>>> q.choice_set.count()
3
>>> Choice.objects.filter(question__pub_date__year=current_year)
<QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>
>>> c = q.choice_set.filter(choice_text__startswith='Just hacking')
>>> c.delete()

本文地址:H5W3 » 【Python】Django 框架中模型的使用

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址