Django forms组件里的ChoiceField、ModelChoiceField和ModelMutipleChoiceField的区别
阅读简要
首先我们要明白Django forms组件里的ChoiceField、ModelChoiceField和ModelMutipleChoiceField是继承关系
ChoiceField
1. Django forms组件中ChoiceField字段是对models里choice的渲染 2. choices作用:在数据库中用元组的第一项作为存储的值,在显示时,将元组的第二项作为显示的内容,便于前端使用下拉框 3. 用get_xxxx_display()显示第二项的值
class Authors(models.Model): name = models.CharField("姓名", max_length=32) gender = models.SmallIntegerField(choices=((1, "男"), (2, "女")), default=1)
ModelChoiceField
1. Django forms组件中ModelChoiceField字段是对models里Forekey的渲染 2. 在前端渲染为下拉菜单
class Book(models.Model): title = models.CharField("书名", max_length=32) publish = models.ForeignKey(to="Publish", on_delete=models.CASCADE, verbose_name="出版社")
ModelMutipleChoiceField
1. Django forms组件中ModelMutipleChoiceField字段是对models里ManyToManyField的渲染
2. 在前端渲染为多选菜单
models.py
class Authors(models.Model): name = models.CharField("姓名", max_length=32) age = models.IntegerField("年龄") gender = models.SmallIntegerField(choices=((1, "男"), (2, "女")), default=1) def __str__(self): return self.name class Book(models.Model): title = models.CharField("书名", max_length=32) publish_time = models.DateField() publish = models.ForeignKey(to="Publish", on_delete=models.CASCADE, verbose_name="出版社") authors = models.ManyToManyField(to="Authors") def __str__(self): return self.title class Publish(models.Model): name = models.CharField("出版社名", max_length=32) address = models.CharField("地址", max_length=32) def __str__(self): return self.name
forms.py
from django import forms class AuthorForm(forms.Form): name = forms.CharField(label="姓名", max_length=32) age = forms.IntegerField(label="年龄") gender = forms.ChoiceField(choices=((1, "男"), (2, "女"))) class BookForm(forms.Form): title = forms.CharField(label="书名", max_length=32) publish_time = forms.DateField(label="发行时间") publish = forms.ModelChoiceField(label="出版社", queryset=Publish.objects.all()) authors = forms.ModelMultipleChoiceField(label="作者", queryset=Authors.objects.all())
别忘记点赞哦! ~.~