Django,获取所有必填字段?

时间:2016-07-14 06:44:55

标签: django

如何获取模型创建所需的所有字段?
(与运行迁移之前的django迁移检查相同?)

3 个答案:

答案 0 :(得分:5)

您可以在模型Meta类中使用get_fields()方法:

fields = MyModel._meta.get_fields()
required_fields = []

# Required means `blank` is False
for f in fields:
    # Note - if the field doesn't have a `blank` attribute it is probably
    # a ManyToOne relation (reverse foreign key), which you probably want to ignore.
    if hasattr(f, 'blank') and f.blank == False:
        required_fields.append(f)   

答案 1 :(得分:3)

上面的答案可以使用列表理解和$i=0; foreach($array as $arr) { if($i==0) { $first_element=$arr; break; } $i++; } echo $first_element; 更简洁地实施,默认值为getattr()

False

答案 2 :(得分:1)

这是获取所有必填字段列表的更彻底的方法。

首先,它从模型中获得所有字段,其中blank = False。 其次,它检查是否为表单类中的任何基本字段设置了required = False。 第三,它会更新列表以为您提供所有必填字段。

此功能不能做的一件事是检查是否手动将required = True设置为表单类的 init 方法中的任何字段。

def get_required_fields(form_class):
    """Get the required fields of a form. Returns a list of field names."""

    def get_blank_not_allowed_fields(model):
        """Get the list of field names where 'blank=False' for the given model."""
        blank_not_allowed_fields = []
        for field in model._meta.get_fields():
            if hasattr(field, 'blank') and field.blank is False:
                blank_not_allowed_fields.append(field.name)
        blank_not_allowed_fields.remove('id')
        return blank_not_allowed_fields

    blank_not_allowed_fields = get_blank_not_allowed_fields(form_class.Meta.model)

    # Even though, for certain fields, blanks are designated to be allowed (aka blank=True)
    # in the model class, they can have 'required' != True in the form class.
    # So, remove all fields where required is not True.
    for field_name, value in form_class.base_fields.items():
        if value.required is not True:
            blank_not_allowed_fields.remove(field_name)

    # At this point, if we are being precise, this variable should be named required_fields 
    # but, there is no point in changing the name of an already declared list.
    return blank_not_allowed_fields