-
Hi, I am trying to define a custom document class for my use to provide some 'dot' access to the main fields of the database. For example, if I have the field 'name' in my database, I would specify the custom class such as this: class MyDocument(Document):
def __init__(self, value, doc_id):
super().__init__(value, doc_id)
self.name = self["name"] Then, in my script I would import TinyDB and assign from tinydb import TinyDB, Query
TinyDB.document_class = MyDocument
db = TinyDB("db.json")
db.insert({"name":"John Smith"}) Then, running Name = Query()
type(db.get(Name.name == "John Smith"))
>>> tinydb.table.Document Whereas I would expect it should be db.document_class
>>> __main__.MyDocument So it looks like it is assigning correctly, but the return is still as a Document? Any hints appreciated! It may well be that I am just using this for completely the wrong thing... Cheers, |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Hey @markbrai, I think I understand this issue: You're adding the
As you can see, the
Then it should work 🙂 |
Beta Was this translation helpful? Give feedback.
-
Perfect! I knew I was missing something basic - I should have noticed this as I was having to import Document from tinydb.table to start with! Working perfectly now - thankyou! |
Beta Was this translation helpful? Give feedback.
Hey @markbrai, I think I understand this issue: You're adding the
document_class
attribute to theTinyDB
class instead of assigning it to theTable
class. You can check this by trying to see thedocument_class
value before trying to change it:As you can see, the
TinyDB
class has no attribute calleddocument_class
. But when you try to assign it, Python will not throw an error but instead create a new attribute for this class. Instead, try setting the property like this: