Reputation: 738
I have Django models with many uncompulsory fields Is there an alternative to avoid null=True
and blank=True
? Is there something like blank_fields = ('email','image',)
and null_fields = ('email', 'image')
?
Upvotes: 3
Views: 222
Reputation: 309089
No, Django does not have any options like blank_fields
or null_fields
.
You could subclass the fields to create optional versions, e.g. OptionalCharField
, but I would recommend against this. It might be less repetitive than using blank=True, null=True
repeatedly, but it will be less readable for other Django developers who look at your code. And as Cezar suggests in the comments you shouldn’t usually use null=True
for CharField
because that means you have two empty values, ''
and None
.
Upvotes: 3
Reputation: 2437
There is nothing which Django provides by default. These attributes are per field definitions, not something which is Model level. You have definitions as unique_together
, index_together
which are model level definitions combining different fields.
One approach can be of subclassing the Fields and provide a default definition -
class CustomIntegerField(models.IntegerField):
def __init__(self, *args, **kwargs):
kwargs['blank'] = True
kwargs['null'] = True
super(CustomIntegerField, self).__init__(**kwargs)
class Test(models.Model):
cus = CustomIntegerField(default=0)
Migration:
class Migration(migrations.Migration):
dependencies = [ ]
operations = [
migrations.CreateModel(
name='Test',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('cus', test.models.CustomIntegerField(blank=True, default=0, null=True)),
],
),
]
You can do this for other fields as well.
Upvotes: 2