diff --git a/src/ttfrog/db/schema/character.py b/src/ttfrog/db/schema/character.py index 459be5b..eb8f080 100644 --- a/src/ttfrog/db/schema/character.py +++ b/src/ttfrog/db/schema/character.py @@ -1,5 +1,6 @@ import itertools from collections import defaultdict +from functools import cached_property from typing import List from sqlalchemy import ForeignKey, String, Text, UniqueConstraint @@ -261,16 +262,21 @@ class Character(BaseObject, SlugMixin, ModifierMixin): ancestry_id: Mapped[int] = mapped_column(ForeignKey("ancestry.id"), nullable=False, default="1") ancestry: Mapped["Ancestry"] = relationship(uselist=False, default=None) - inventories: Mapped[List["Inventory"]] = relationship( + _inventories: Mapped[List["Inventory"]] = relationship( uselist=True, cascade="all,delete,delete-orphan", lazy="immediate", default_factory=lambda: [] ) _hit_dice = relationship("HitDie", uselist=True, cascade="all,delete,delete-orphan", lazy="immediate") _spell_slots = relationship("SpellSlot", uselist=True, cascade="all,delete,delete-orphan", lazy="immediate") - @property + @cached_property + def inventories(self): + return dict([(inventory.inventory_type, inventory) for inventory in self._inventories]) + + @cached_property def spells(self): - return [inv for inv in self.inventories if inv.inventory_type == InventoryType.SPELL][0] + return self.inventories[InventoryType.SPELL] + @property def prepared_spells(self): @@ -393,9 +399,9 @@ class Character(BaseObject, SlugMixin, ModifierMixin): def class_features(self): return dict([(mapping.class_feature.name, mapping.option) for mapping in self.character_class_feature_map]) - @property + @cached_property def equipment(self): - return [inv for inv in self.inventories if inv.inventory_type == InventoryType.EQUIPMENT][0] + return self.inventories[InventoryType.EQUIPMENT] @property def equipped_items(self): @@ -661,6 +667,6 @@ class Character(BaseObject, SlugMixin, ModifierMixin): ): self.add_skill(skill, proficient=False, expert=False) - self.inventories.append(Inventory(inventory_type=InventoryType.EQUIPMENT, character_id=self.id)) - self.inventories.append(Inventory(inventory_type=InventoryType.SPELL, character_id=self.id)) + self._inventories.append(Inventory(inventory_type=InventoryType.EQUIPMENT, character_id=self.id)) + self._inventories.append(Inventory(inventory_type=InventoryType.SPELL, character_id=self.id)) session.add(self)