zoukankan      html  css  js  c++  java
  • 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())

     别忘记点赞哦!     ~.~

  • 相关阅读:
    C#中AppDomain.CurrentDomain.BaseDirectory及各种路径获取方法
    Windows 2008 server R2安装.NET Framework4时提示“灾难性故障”
    Mysql explain执行计划
    解决Linux c语言运行时候“段错误 (核心已转储)”问题-采用gdb 解决
    udp-->socket通信原理
    udp通信的原理---makefile文件
    c语言知识点
    linux系统man命令用法和安装方法
    <linux系统c语言生成.so文件,生成64位可执行文件,在64位系统中运行32位的可执行文件>
    ubuntu系统无eth0网卡解决办法
  • 原文地址:https://www.cnblogs.com/pungchur/p/11969844.html
Copyright © 2011-2022 走看看