Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django, get all required fields?

Tags:

django

How can I get all the fields that is required for a model to be created?
(same as django migrations check before running migrations?)

like image 738
eugene Avatar asked Oct 17 '25 19:10

eugene


1 Answers

You can use the get_fields() method on the model Meta class:

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 getattr(f, 'blank', False):
        required_fields.append(f)   
like image 147
solarissmoke Avatar answered Oct 19 '25 13:10

solarissmoke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!