Hello,
I have a simple class that looks like the following:
class Person(DocType):
name = Text(fields={
'keyword': Keyword(),
})
date_created = Date()
seen_count = Integer()
...
I would like to default the date_created field to now and the seen_count field to 1 and set other defaults for fields not listed here.
I found this test that shows a default being set by using the clean function of an intermediate class. https://github.com/elastic/elasticsearch-dsl-py/blob/master/test_elasticsearch_dsl/test_validation.py#L27
Since the commit is from 2 years ago, I'm wonder if this is still the easiest/best/proper way to do field defaults. Thanks for the help!
Hi, that is definitely one way to do it, but I would recommend more for a field that you then wish to reuse. If you have a document that you wish to have some default values for, I'd personally just override .save() and set the values there if they are not set.
Hope this helps!
I'm also looking at setting some default values on object creation.
@HonzaKral what if you want to reference the default values before .save() has been called?
class Thing(DocType):
uuid = Keyword()
# your suggestion
def save(self, **kwargs):
self.uuid = uuid.uuid4()
return super().save(**kwargs)
thing = Thing()
# but what if I want to access the generated UUID before I've called .save()?
print(thing.uuid)
thing.save()
A use case would be, for example, initializing other fields that depend on a field being set to datetime.now() or a UUID or some other default value.
I'm currently defining my own init() method and using that after instantiating the object. Just wondering if there's a recommended way to do it?
Most helpful comment
I'm also looking at setting some default values on object creation.
@HonzaKral what if you want to reference the default values before
.save()has been called?A use case would be, for example, initializing other fields that depend on a field being set to
datetime.now()or a UUID or some other default value.I'm currently defining my own
init()method and using that after instantiating the object. Just wondering if there's a recommended way to do it?