创立模型
polls/models.pyfrom django.db import modelsclass 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.pyINSTALLED_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.id1>>> q.question_text"What's new?">>> q.pub_datedatetime.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.pyimport datetimefrom django.db import modelsfrom django.utils import timezoneclass 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()