zoukankan      html  css  js  c++  java
  • Django--models字段参数 limit_choices_to

    在models中,字段参数limit_choices_to的用法

    在使用ModelForm渲染前端页面的时候,当model字段为ForeignKey的时候,会被渲染成select单选框, model字段为ManyToMany的时候会被渲染成多选select款。

    当你在model中FK字段或者M2M字段中加上 limit_choices_to选项的时候,前端页面的渲染会根据你的限制条件来展示,这样就达到来限制用户选择的目的

    class ClassList(models.Model):
        """
        班级表
        """
        school = models.ForeignKey(verbose_name='校区', to='School', on_delete=models.CASCADE)
        course = models.ForeignKey(verbose_name='课程名称', to='Course', on_delete=models.CASCADE)
        semester = models.PositiveIntegerField(verbose_name='班级(期)')
        price = models.PositiveIntegerField(verbose_name='学费')
        start_date = models.DateField(verbose_name='开班日期')
        graduate_date = models.DateField(verbose_name='结业日期', null=True, blank=True)
        class_teacher = models.ForeignKey(verbose_name='班主任', to='UserInfo', related_name='classes',
                                          on_delete=models.CASCADE, limit_choices_to={'depart__title': '教质部'})
        tech_teachers = models.ManyToManyField(verbose_name='任课老师', to='UserInfo', related_name='teach_classes',
                                               limit_choices_to={'depart__title__in': ['Python教学部', 'Linux教学部']})
        memo = models.TextField(verbose_name='说明', null=True, blank=True)

    从上面的model字段可以看出, class_teacher字段限制了选择条件:{'depart__title': '教质部'}, 即在选择班主任的时候,只能选择关联班主任的外键表depart中名称为教质部的数据

     

    ManyToMany字段的limit_choices_to指向了 {'depart__title__in':['xx','xx']} 一个列表,那在前端中只能选择这个列表中的数据

  • 相关阅读:
    概述反射和序列化
    读书笔记6pandas简单使用
    读书笔记5基于matplotlib画图
    读书笔记4数据的读入和保存
    读书笔记3数组的一些常用函数
    introduction to python for statistics,analysis笔记3
    introduction to python for statistics,analysis笔记2
    introduction to anaconda
    图像的线性空间滤波matlab实现
    C-I/O操作函数详解
  • 原文地址:https://www.cnblogs.com/aaaajayheng1990/p/11045986.html
Copyright © 2011-2022 走看看