Custom Model Fields
Django model에서 사용하는 fields를 상속받아 수정하는 방식이다.
from django.db import models class NullCharField(models.CharField): """ CharField with Null & Blank """ def __init__(self, *args, **kwargs): kwargs['blank'] = True kwargs['null'] = True super(NullCharField, self).__init__(self, *args, **kwargs) class NullBigIntegerField(models.BigIntegerField): """ BigIntegerField with Null & Blank """ def __init__(self, *args, **kwargs): kwargs['blank'] = True kwargs['null'] = True super(NullBigIntegerField, self).__init__(self, *args, **kwargs) class NullSmallIntegerField(models.SmallIntegerField): """ SmallIntegerField with Null & Blank """ def __init__(self, *args, **kwargs): kwargs['blank'] = True kwargs['null'] = True super(NullSmallIntegerField, self).__init__(self, *args, **kwargs) class NullIntegerField(models.IntegerField): """ IntegerField with Null & Blank """ def __init__(self, *args, **kwargs): kwargs['blank'] = True kwargs['null'] = True super(NullIntegerField, self).__init__(self, *args, **kwargs)
위의 코드는 Null=True와 Blank=True를 반복하여 사용하기 싫어서 만든 것이다.
수정 전
from django.db import models class TestModel(models.Model): id = models.AutoField(primary_key=True) age = models.IntegerField(blank=True, null=True) name = models.CharField(blank=True, null=True)
수정 후
from common import fields class TestModel(models.Model): id = models.AutoField(primary_key=True) age = fields.NullIntegerField() name = fields.NullCharField()
'Python > Django' 카테고리의 다른 글
[Django] uwsgi + nginx in ubuntu (0) | 2016.10.18 |
---|---|
[Django] Test (0) | 2016.10.12 |
[Django] Extra (0) | 2016.10.06 |
[Django] Filter vs Exclude (0) | 2016.10.04 |
[Django] Abstract Model (0) | 2016.09.29 |
댓글