2👍
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.
3👍
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
.
- [Django]-How to test admin change views?
- [Django]-How to filter a queryset of objects created more than one hour ago from Django's DateTimeField?
- [Django]-How do I compare DateTime objects to UNIX timestamps when filtering results in django?