Comments (2)
Hi @hd10180 ,
Thank you for the issue. Please use event Save
for this case. Save
and SaveChanges
are different and use different events.
import asyncio
from datetime import datetime
from beanie import (
Document,
Insert,
Replace,
SaveChanges,
Save,
after_event,
before_event,
init_beanie,
)
from motor.motor_asyncio import AsyncIOMotorClient
from pydantic import BaseModel, Field
class Users(Document):
name: str
enabled: bool = True
desc: str | None = None
created: datetime = Field(default_factory=datetime.utcnow)
# !附加检查
@before_event([Insert, Replace, SaveChanges, Save])
def checker_before(self):
print("before..............")
if not self.desc:
del self.desc
@after_event([Insert, Replace, SaveChanges, Save])
def checker(self):
print("after...............")
if not self.desc:
del self.desc
class Settings:
name = "users"
use_state_management = True
class UpdateUsers(BaseModel):
enabled: bool | None = None
desc: str | None = None
async def main():
import beanie
print(f"beanie version: {beanie.__version__}")
cli = AsyncIOMotorClient("mongodb://beanie:beanie@localhost:27017")
db = cli["test_wrong_collection"]
await db.drop_collection(Users.Settings.name)
await db[Users.Settings.name].insert_one(
{"name": "lucy", "enabled": True, "created": datetime.utcnow()}
)
print(await db[Users.Settings.name].find_one({"name": "lucy"}))
await init_beanie(db, document_models=[Users])
test_user = Users(name="hello")
await test_user.save()
print(await db[Users.Settings.name].find_one({"name": "hello"}))
asyncio.run(main())
from beanie.
Hi @hd10180 , Thank you for the issue. Please use event
Save
for this case.Save
andSaveChanges
are different and use different events.import asyncio from datetime import datetime from beanie import ( Document, Insert, Replace, SaveChanges, Save, after_event, before_event, init_beanie, ) from motor.motor_asyncio import AsyncIOMotorClient from pydantic import BaseModel, Field class Users(Document): name: str enabled: bool = True desc: str | None = None created: datetime = Field(default_factory=datetime.utcnow) # !附加检查 @before_event([Insert, Replace, SaveChanges, Save]) def checker_before(self): print("before..............") if not self.desc: del self.desc @after_event([Insert, Replace, SaveChanges, Save]) def checker(self): print("after...............") if not self.desc: del self.desc class Settings: name = "users" use_state_management = True class UpdateUsers(BaseModel): enabled: bool | None = None desc: str | None = None async def main(): import beanie print(f"beanie version: {beanie.__version__}") cli = AsyncIOMotorClient("mongodb://beanie:beanie@localhost:27017") db = cli["test_wrong_collection"] await db.drop_collection(Users.Settings.name) await db[Users.Settings.name].insert_one( {"name": "lucy", "enabled": True, "created": datetime.utcnow()} ) print(await db[Users.Settings.name].find_one({"name": "lucy"})) await init_beanie(db, document_models=[Users]) test_user = Users(name="hello") await test_user.save() print(await db[Users.Settings.name].find_one({"name": "hello"})) asyncio.run(main())
thanks.
Sorry for taking up your time, it works fine
from beanie.
Related Issues (20)
- [BUG] Fetching Links in view raises AttributeError: _database_major_version HOT 2
- [BUG] Double return in sources code of class beanie.odm.fields.Link HOT 4
- [BUG] Beanie projection and Pydantic Schema do not play well together HOT 6
- [BUG] before_event not working with validate_on_save = True HOT 2
- [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 2
- 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
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.