Implement sync_from_state method for Area, Brand, Item, RoomFunction, and Room models; streamline entity management in settings
This commit is contained in:
parent
87fa623cde
commit
8a5c5db9e0
11 changed files with 204 additions and 70 deletions
|
@ -28,4 +28,34 @@ class Item(db.Model):
|
|||
'id': self.id,
|
||||
'name': self.description,
|
||||
'category': self.category
|
||||
}
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def sync_from_state(cls, submitted_items: list[dict]):
|
||||
"""
|
||||
Syncs the Items table with the provided list of dictionaries.
|
||||
Adds new items and removes items that are not in the list.
|
||||
"""
|
||||
submitted = {
|
||||
str(item.get("name", "")).strip()
|
||||
for item in submitted_items
|
||||
if isinstance(item, dict) and str(item.get("name", "")).strip()
|
||||
}
|
||||
|
||||
existing_query = db.session.query(cls)
|
||||
existing = {item.description: item for item in existing_query.all()}
|
||||
|
||||
existing_descriptions = set(existing.keys())
|
||||
|
||||
print(f"Existing items: {existing_descriptions}")
|
||||
print(f"Submitted items: {submitted}")
|
||||
print(f"items to add: {submitted - existing_descriptions}")
|
||||
print(f"items to remove: {existing_descriptions - submitted}")
|
||||
|
||||
for description in submitted - existing_descriptions:
|
||||
db.session.add(cls(description=description))
|
||||
print(f"➕ Adding item: {description}")
|
||||
|
||||
for description in existing_descriptions - submitted:
|
||||
db.session.delete(existing[description])
|
||||
print(f"🗑️ Removing item: {description}")
|
Loading…
Add table
Add a link
Reference in a new issue