django搭建web (四) models.py

demo

該demo模型主要是用於問題,選擇單個或多個答案的問卷形式應用html

# -*- 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中的字段,或者註釋起來python

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

這裏建立了兩個模型,都是繼承自modelsdjango

在第一個模型myQuestion中,max_length表示此處可填字段最大長度,

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

一句choices = choice_style爲模型建立了一個下拉框,choice_style是前面代碼定義的一個tuple以下所示:

下句是爲了問題不展開時,能夠以本question_text做爲標題顯示

def __unicode__(self):
    return self.question_text

如下語句是創建一對多關係(外鍵),一個答案可對應多個問題,具體可查---ORM

questions = models.ForeignKey(myQuestion)

如下語句設置了一個int型變量answer_votes,並初始化爲0

answer_votes = models.IntegerField(default = 0)
相關文章
相關標籤/搜索