Comments (4)
Frozen models don't work either, but I guess this is expected because of the id
field.
It'd be really nice if it was possible to mark a model as ConfigDict(frozen=True)
and have this apply to all fields except the id
field. But I guess that might be a bigger ask.
For completeness, here's a reproduction case for a frozen=True model in Pydantic 2:
from pydantic import Field, ConfigDict
from motor.motor_asyncio import AsyncIOMotorClient
from beanie import Document, init_beanie
class TestFrozen(Document):
model_config = ConfigDict(frozen=True)
some_field: str
class Settings:
name = "test_frozen"
async def test_frozen():
await init_beanie(database=client[DB_NAME], document_models=[TestFrozen])
test_frozen = TestFrozen(some_field="test")
await test_frozen.save()
# also fails with test_frozen.insert()
await test_frozen()
Result:
File ~/venv/pq_dev/lib/python3.11/site-packages/beanie/odm/documents.py:719, in Document.update(self, ignore_revision, session, bulk_writer, skip_actions, skip_sync, *args, **pymongo_kwargs)
717 if use_revision_id and not ignore_revision and result is None:
718 raise RevisionIdWasChanged
--> 719 merge_models(self, result)
720 return self
File ~/venv/pq_dev/lib/python3.11/site-packages/beanie/odm/utils/parsing.py:46, in merge_models(left, right)
44 left.__setattr__(k, right_value)
45 elif not isinstance(right_value, Link):
---> 46 left.__setattr__(k, right_value)
File ~/venv/pq_dev/lib/python3.11/site-packages/pydantic/main.py:786, in BaseModel.__setattr__(self, name, value)
783 self.__pydantic_private__[name] = value
784 return
--> 786 self._check_frozen(name, value)
788 attr = getattr(self.__class__, name, None)
789 if isinstance(attr, property):
File ~/venv/pq_dev/lib/python3.11/site-packages/pydantic/main.py:850, in BaseModel._check_frozen(self, name, value)
844 return
845 error: pydantic_core.InitErrorDetails = {
846 'type': typ,
847 'loc': (name,),
848 'input': value,
849 }
--> 850 raise pydantic_core.ValidationError.from_exception_data(self.__class__.__name__, [error])
ValidationError: 1 validation error for TestFrozen
id
Instance is frozen [type=frozen_instance, input_value=ObjectId('65d09abca8cf98113d6784ca'), input_type=PydanticObjectId]
For further information visit https://errors.pydantic.dev/2.6/v/frozen_instance
from beanie.
Possible workaround for frozen fields:
- Use
state_management = True
inSettings
- Then use
.save_changes()
instead of.save()
or.update()
- So far this seems to work, because
.save_changes()
only updates the fields which have changed, and frozen fields can never change because of Pylance's protection.
I'm still testing this to confirm there's no edge cases, but this might be a usable workaround for me.
I'd still raise the .save()
issue as a bug though, because IMHO it should be possible for Beanie to detect frozen fields and not try to update them.
from beanie.
Unfortunately I don't think the state_management=True work around works, at least not if links are used.
Because I also get the frozen fields exception when I do something like:
from beanie import Document, Link, WriteRules
from pydantic import Field
class Door(Document):
height: int = Field(default=2, frozen=True)
width: int = 1
class House(Document):
name: str
door: Link[Door]
door = Door(height=10, width=20)
house = House(name="test", door=door)
await house.insert(link_rule=WriteRules.WRITE)
Even though nothing has changed on Door.height
, the act of inserting it with link_rule
seems to cause the model to get re-written, triggering the frozen error.
from beanie.
Hi! Good catch. I'll add a test suite for this and will fix on the next bug-fixing session.
from beanie.
Related Issues (20)
- [BUG] ModuleNotFoundError when importing models in a migration module HOT 1
- [BUG]before_event bug HOT 4
- [BUG] Missing documentation for `beanie.odm.BulkWriter` HOT 1
- [BUG] (some) type annotations for session wrong HOT 3
- [BUG] type annotation for init_beanie() should use Sequence
- [BUG] before_event of type Update HOT 4
- [BUG] mypy does not raise error when trying to access a non-existing attribute from a beanie Document. HOT 1
- [BUG] Indexed unique will not work after Field regex. HOT 2
- [BUG] Empty BackLink for `Optional[BackLink[ADoc]]` when document has no back-link HOT 3
- Concerns and Suggestions Regarding Beanie Library HOT 2
- [Doc] Document for soft delete feature HOT 1
- [BUG] Order of elements in list[Link] is not preserved HOT 2
- [BUG] pydantic computed properties omitted during `insert_many` operation on Document
- [BUG] get_motor_collection() returning None under volume only HOT 1
- [BUG] search criteria not using pydantic Field alias to set the key.
- [BUG] `PydanticObjectId` isn't properly configured when deserializing from JSON
- depth search "find(Teste.item1.item2.item3.id == id)" [BUG]
- [BUG] Link not working in find queries on fields with alias
- [BUG]
- [BUG] BulkWriter does not allow unordered bulks
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from beanie.