Auto increment field #693
Unanswered
humbertogontijo
asked this question in
Question
Replies: 1 comment 2 replies
-
Here's what I use for auto increment documents: from typing import ClassVar
import beanie
from beanie.odm.operators.update.general import Inc
class CounterDocument(beanie.Document):
id: str
n: int = 0
class Settings:
name = "counters"
async def increment(self) -> int:
await self.update(Inc({CounterDocument.n: 1}), upsert=True)
return self.n
class AutoIncrementDocument(beanie.Document):
id: int | None = None
_counter: ClassVar[CounterDocument]
@classmethod
def set_collection(cls, collection):
super().set_collection(collection)
cls._counter = CounterDocument(id=collection.name)
async def insert(self, **kwargs):
if self.id is None:
self.id = await self._counter.increment()
return await super().insert(**kwargs)
async def update(self, *args, **kwargs):
if self.id is None:
self.id = await self._counter.increment()
return await super().update(*args, **kwargs) It needs this fix, otherwise Beanie raises You can use it by simply subclassing your document from class MyDocument(AutoIncrementDocument):
name: str
...
async def init(database):
await beanie.init_beanie(document_models=[CounterDocument, MyDocument], database=database) |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Is it possible to create a auto incremental field with beanie? If so, how to?
A short unique identifier also works
Beta Was this translation helpful? Give feedback.
All reactions