Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Anyway to activate function after create Model? #221

Open
Chetchaiyan opened this issue Jan 9, 2024 · 2 comments
Open

Anyway to activate function after create Model? #221

Chetchaiyan opened this issue Jan 9, 2024 · 2 comments

Comments

@Chetchaiyan
Copy link

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
Copy link
Collaborator

ADR-007 commented Jan 9, 2024

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
Copy link
Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants