Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Document ID and existing unique value in the document #545

Open
aptly-io opened this issue Nov 8, 2023 · 1 comment
Open

Document ID and existing unique value in the document #545

aptly-io opened this issue Nov 8, 2023 · 1 comment

Comments

@aptly-io
Copy link

aptly-io commented Nov 8, 2023

When inserting documents and knowing a certain document property value (e.g. house-id) is unique, is there a way to tell tinydb to use that house-id as document ID?

Just found #351

The document_id_class is a class variable, it's for all tinydb's Table (looks not ideal at first sight).

Would this approach make sense:
When inserting a new Mapping, first make it a Document(mapping, mapping.house-id) (where the doc_id equal to the house-id).
However Document needs an int type doc_it. Should one also subclass Document to customize the doc_id's type and change the Table's document_class?
When creating a Table sub-class, one also has to create TinyDB sub-class to modify its class variable table_class?

Is there a more elegant approach that I'm overlooking?

@aptly-io
Copy link
Author

aptly-io commented Nov 8, 2023

This might be a recipe for others when a str as doc_id:

class _Document(dict):
    def __init__(self, value: Mapping, doc_id: str):
        super().__init__(value)
        self.doc_id = doc_id

class _Table(Table):
    document_class = _Document
    document_id_class = str
    def _get_next_id(self):
        raise NotImplementedError("doc_id should be self provided")

class _TinyDB(TinyDB):
    table_class = _Table


class Model:

    def __init__(self):
        self._db = _TinyDB("db.json")

There are some issue with table.py though when using _Document ...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant