Are they typed in below same?
The first code which defines fields in class attribute section is recommended by django documents
class Musician(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
instrument = models.CharField(max_length=100)
The second code which I want to use defines fields in init function.
class Musician(models.Model):
def __init__(self, *args, **kwargs):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
instrument = models.CharField(max_length=100)
super().__init__(*args, **kwargs)
I want to use second codes when I define classmethod in Model to define functions validateing fields like below.
class HyperLinks(model.Model):
def __init__(self, *args, **kwargs):
self.links = models.JSONField(default=[], validators=[self.validate_links])
super().__init__(*args, **kwargs)
@staticmethod
def validate_links(data):
"""
example
links = [("github", "https://github.com/yeop-sang"), ("homepage", "http://yeop.kr")]
"""
if type(data) is not list:
raise ValidationError(
'links should be list'
)
for datum in data:
if type(datum) is not tuple:
raise ValidationError(
'links should be list contained tuple'
)
if len(datum) is not 2:
raise ValidationError(
'link should be contain type and link'
)
if not (type(datum[0]) is str or type(datum[1]) is str):
raise ValidationError(
'link and type should be string'
)