Skip to content

Commit

Permalink
feat: add RecordID serialization for model_dump
Browse files Browse the repository at this point in the history
- Added field_serializer for id in ObjectModel
- Added documentation about RecordID serialization
- Bumped version to 0.1.4
  • Loading branch information
lfnovo committed Jan 3, 2025
1 parent b70b13e commit 8a4c3c1
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 5 deletions.
24 changes: 24 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,30 @@ print(f"Created at: {user.created}") # Automatically set
print(f"Updated at: {user.updated}") # Automatically set
```

### RecordID Serialization

When using `RecordID` fields in your models, you should add a field serializer to properly convert them to strings when using `model_dump()`. Here's an example:

```python
from pydantic import field_serializer
from surrealdb import RecordID

class User(ObjectModel):
table_name = "user"
name: str

class Post(ObjectModel):
table_name = "post"
title: str
author: RecordID # Reference to a User

@field_serializer('author')
def serialize_author(self, author: RecordID) -> str:
return str(author)
```

Note: The base `ObjectModel` already handles the serialization of the `id` field.

## Configuration

### Database Connection
Expand Down
4 changes: 2 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "surrantic"
version = "0.1.3"
version = "0.1.4"
description = "A simple Pydantic ORM implementation for SurrealDB"
readme = "README.md"
authors = [
Expand All @@ -21,7 +21,7 @@ classifiers = [
]
dependencies = [
"pydantic>=2.0.0",
"python-dotenv>=1.0.1",
"python-dotenv>=1.0.0",
"surrealdb>=0.3.0",
]

Expand Down
8 changes: 7 additions & 1 deletion src/surrantic/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
Type, TypeVar, Union)

from dotenv import load_dotenv
from pydantic import BaseModel
from pydantic import BaseModel, field_serializer
from surrealdb import AsyncSurrealDB, RecordID, SurrealDB # type: ignore

from .logging_config import setup_logging
Expand Down Expand Up @@ -112,6 +112,12 @@ class ObjectModel(BaseModel):
created: Optional[datetime] = None
updated: Optional[datetime] = None

@field_serializer('id')
def serialize_id(self, value: Optional[RecordID]) -> Optional[str]:
if value is None:
return None
return str(value)

@staticmethod
def _format_datetime_z(dt: datetime) -> str:
"""Format datetime in ISO format with Z instead of +00:00.
Expand Down
4 changes: 2 additions & 2 deletions uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 8a4c3c1

Please sign in to comment.