• 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())

     别忘记点赞哦!     ~.~

  • 相关阅读:
    Vue 实现前进刷新,后退不刷新的效果
    chrome浏览器的跨域设置——包括版本49前后两种设置
    Promise.all和Promise.race区别,和使用场景
    滚动条默认最底部
    使用react进行父子组件传值
    java 数组基础学习(一维二维数组)
    react项目 使用echarts
    Python的hasattr() getattr() setattr() 函数使用方法详解
    【线性判别】Fisher线性判别(转)
    【semantic segmentation】Pyramid Scene Parsing Network(转)
  • 原文地址:https://www.cnblogs.com/pungchur/p/11969844.html
Copyright © 2020-2023  润新知