当前位置: 首页 > 后端技术 > Python

Django框架中模型的使用

时间:2023-03-25 20:18:13 Python

创建模型polls/models.pyfromdjango.dbimportmodelsclassQuestion(models.Model):question_text=models.CharField(u'questioncontent',max_length=200,null=False,default='')pub_date=models.DateTimeField(u'time')classChoice(models.Model):question=models.ForeignKey(Question,on_delete=models.CASCADE,verbose_name="questionID")choice_text=models.CharField(u'optioncontent',max_length=200,null=False,default='')votes=models.PositiveIntegerField(u'PositiveIntegerField',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',]生成迁移文件:>pymanage.pymakemigrationspolls查看迁移文件内容:>pymanage.pysqlmigratepolls0001运行迁移:>pymanage.pymigratetestmodelAPI>pymanage.pyshell>>>从polls.models导入选择,问题>>>Question.objects.all()>>>fromdjango.utilsimporttimezone>>>q=Question(question_text="What'snew?",pub_date=timezone.now())>>>q.save()>>>q.id1>>>q.question_text“有什么新消息?”>>>q.pub_datedatetime.datetime(2012,2,26,13,0,0,775217,tzinfo=)>>>q.question_text="怎么了?">>>q.save()>>>Question.objects.all()]>编辑Question模型的代码以更改对象的输出:#polls/models.pyimportdatetimefromdjango.dbimportmodelsfromdjango.utilsimporttimezoneclassQuestion(models.Model):#...def__str__(self):returnself.question_textdefwas_published_recently(self):返回自我。pub_date>=timezone.now()-datetime.timedelta(days=1)classChoice(models.Model):#...def__str__(self):returnself.choice_text重新打开交互式命令行:>pymanage.py外壳>>>frompolls.modelsimportChoice,Question>>>Question.objects.all()]>>>>Question.objects.filter(id=1)]>>>>Question.objects.filter(question_text__startswith='What')]>>>>fromdjango.utilsimporttimezone>>>current_year=timezone.now().year>>>Question.objects.get(pub_date__year=current_year)#查询不存在的ID会抛出异常>>>Question.objects.get(id=2)DoesNotExist:问题匹配查询不存在#通过主键查询>>>q=Question.objects.get(pk=1)>>>q.was_published_recently()True#关联查询问题的选项>>>q.choice_set.all()#创建选项数据>>>q.choice_set.create(choice_text='Notmuch',votes=0)>>>q.choice_set.create(choice_text='Thesky',votes=0)<选择:天空>>>>c=q.choice_set.create(choice_text='Justhackingagain',votes=0)>>>c.question#关联查询问题的选项>>>q.choice_set.all(),,]>>>>q.choice_set.count()3>>>Choice.objects.filter(question__pub_date__year=current_year),,]>>>>c=q.choice_set.filter(choice_text__startswith='Justhacking')>>>c.删除()