django展示choice欄位
阿新 • • 發佈:2021-12-24
class Student(models.Model):
sex_choices = (
(0, "女"),
(1, "男"),
(2, "保密"),
)
name = models.CharField(max_length=32, unique=True, verbose_name="姓名")
age = models.SmallIntegerField(verbose_name="年齡", default=18) # 年齡
sex = models.SmallIntegerField(choices=sex_choices)
birthday = models.DateField()
# 一對多的關係:在資料庫建立一個關聯欄位:clas_id
clas = models.ForeignKey(to="Clas",related_name="student_list",on_delete=models.CASCADE)
# 一對一的關係:建立關聯欄位,在資料庫中生成關聯欄位:stu_detail_id
stu_detail = models.OneToOneField("StudentDetail",related_name="stu",on_delete=models.CASCADE)
# 多對多的關係:建立第三張關係表
courses = models.ManyToManyField("Course",related_name="students", db_table="db_student2course")
class Meta:
db_table = "db_student"
def __str__(self):
return self.name
<thead> <tr> <th>序號</th> <th>姓名</th> <th>年齡</th> <th>性別</th> <th>生日</th> <th>班級</th> <th>選修課程</th> </tr> </thead> <tbody> {% for student in student_list %} <tr> <td>{{ forloop.counter }}</td> <td>{{ student.name }}</td> <td>{{ student.age }}</td> <td>{{ student.get_sex_display }}</td> <td>{{ student.birthday|date:'Y-m-d' }}</td> <td>{{ student.clas.name }}</td> <td> {% for course in student.courses.all %} <button>{{ course.title }}</button> {% endfor %} </td> </tr> {% endfor %} </tbody>