#๐Ÿ”’ Trouble with unmapped field in SQLAlchemy + dataclass

8 messages ยท Page 1 of 1 (latest)

shadow nymph
#

I'm having some trouble with SQLAlchemy model that I want to have a unmapped field to act as a cache.

class PM(MappedAsDataclass, AsyncAttrs, LegacyBase):
    __tablename__ = "pms"
    __allow_unmapped__ = True

    history_ids: Mapped[List[int]] = mapped_column(
        "history", JSON(), default_factory=list
    )

    _history: list["PM"] = field(init=False, default_factory=list)

    async def get_history(self):
        if not self._history:
            session = object_session(self)
            if not session:
                raise Exception("No session")
            self._history = list(
                session.scalars(
                    select(PM)
                    .where(PM.id.in_(self.history_ids))
                    .order_by(PM.datestamp.asc())
                    .options(joinedload(PM.recipient), joinedload(PM.sender))
                )
            )

        return self._history

With this code, I'm getting AttributeError: 'PM' object has no attribute '_history'. Did you mean: 'get_history'? and I don't know why. I tried adding __allow_unmapped__ = True and also adding repr=False to the field. I'd love to learn what I've done wrong.

normal plumeBOT
#

Hey @shadow nymph!

Please edit your message to use a code block

Add a py after the three backticks.

```py
print('Hello, world!')
```

This will result in the following:

print('Hello, world!')```
normal plumeBOT
#

@shadow nymph

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

real ravine
#

I donโ€™t know how SqlAlchemy works or what black magic it performs. But You have first defined _history as a class variable, and then you create an instance variable with the same name. So that could be causing some confusion.

shadow nymph
#

Based on what I've researched so far, this seems to be an issue with the dataclass side? I dono for sure though...

real ravine
#

where are you trying to access the _history attribute? What's the full stack trace? What does _history: list["PM"] = field(init=False, default_factory=list) do? does "init=False" mean it doesn't initialize that attribute in the init method?

normal plumeBOT
#
Python help channel closed for inactivity

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.