octabytes / FireO

Google Cloud Firestore modern and simplest convenient ORM package in Python. FireO is specifically designed for the Google's Firestore
https://fireo.octabyte.io
Apache License 2.0
247 stars 29 forks source link

Anyway to activate function after create Model? #221

Open Chetchaiyan opened 8 months ago

Chetchaiyan commented 8 months ago

I would like to run function after I create or retrieve object from firestore. Let's say...

class A(models.Model):
    firestore_1 = models.TextField()

Let's say I retrieve instance of A from firestore via get_by_id() or fetch() which set firestore_1 to "xxx" or "yyy" then I want it initialize context base on data in firestore_1 (after retrieved)

I try to do the following

class A(models.Model):

    def __init__(self):
        super().__init__()
        self.context = Context(self.firestore_1)

However, I found out that when I get data from firestore self.context run before firestore_1 has been set

I can't find the way to automatic run code after instance has finish created with value. Please advise

ADR-007 commented 8 months ago

Hi @Chetchaiyan, you can use lazy evaluation by using cached property:

class A(models.Model):

  @functools.cachedproperty
  def context(self):
    return Context(self.firestore_1)

Another option is to override populate_from_doc which is called on loading model from firestore:

class A(models.Model):
  def populate_from_doc(self, doc: DocumentSnapshot) -> None:
    super().populate_from_doc(doc)
    self.context = Context(self.firestore_1)

Note: this behavior may be changed in the future version without warning

Chetchaiyan commented 8 months ago

Thank you very much. populate_from_doc() is what I'm looking for