django搭建web (四) models.py

demo

该demo模型主要是用于问题,选择单个或多个答案的问卷形式应用

# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
# Create your models here.
choice_style = (
('r','radio'),
('c','checkbox')
) class myQuestion(models.Model):
question_text = models.CharField(max_length = 600)
question_style = models.CharField(max_length = 1,choices = choice_style) def __unicode__(self):
return self.question_text class myAnswer(models.Model):
answer_text = models.CharField(max_length = 200)
questions = models.ForeignKey(myQuestion)
answer_votes = models.IntegerField(default = 0)
def __unicode__(self):
return self.answer_text

同时!要修改admin.py中的字段,或者注释起来

class myQuestion(admin.ModelAdmin):
# fieldsets = [
# (None, {'fields': ['question_text']}),
# ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
# ]
inlines = [ChoiceInline]
#list_display = ('question_text', 'pub_date')

这里创建了两个模型,都是继承自models

在第一个模型myQuestion中,max_length表示此处可填字段最大长度,

question_style = models.CharField(max_length = 1,choices = choice_style)

一句choices = choice_style为模型创建了一个下拉框,choice_style是前面代码定义的一个tuple如下所示:

django搭建web (四) models.py

下句是为了问题不展开时,可以以本question_text作为标题显示

def __unicode__(self):
return self.question_text

以下语句是建立一对多关系(外键),一个答案可对应多个问题,具体可查---ORM

questions = models.ForeignKey(myQuestion)

以下语句设置了一个int型变量answer_votes,并初始化为0

answer_votes = models.IntegerField(default = 0)
上一篇:针对JS经典题型对全局变量及局部变量的理解浅谈


下一篇:我的母校zbvc试做