如何将mongoengine.Document的继承添加到现有类中

问题描述

我有一个Book,该类应继承自mongoengine.Document

from mongoengine import Document
from mongoengine import StringField


class Book(Document):
    title = StringField()
    author = StringField()
    shelf = IntField()
    room = IntField()

    def __init__(self,title=None,author=None,position_tag=None,*args,**kwargs):
        super(Document,self).__init__(*args,**kwargs)

        self.title = title
        self.author = author

        if position_tag:
            # position tag is room#shelf
            self.room,self.shelf = position_tag.split("#")

    @property
    def id(self):
        """Custom id of the document,I want to avoid autogenerated ObjectID()"""
        return f'{self.room}-{self.shelf}-{self.title}'

    def get_price_of_all_books_in_corporation(self,author):
        pass

test_book = Book(title="Some_Title",author="Mark Twain",positon_tag="205.1#5")
test_book.save()  # should be saved with id "205.1-5-Some_Title"
test_book.get_price_of_all_books_in_corporation('William Shakespeare')

我想在项目的其他地方也使用Book对象,因此在实例化新的Book对象时需要添加对其他参数的支持,例如position_tag。此示例仍然以某种方式仍生成具有随机ObjectID的文档。我还尝试添加一个类字段id = StringField(primary_key=True),但对我来说并没有解决问题。通常,这是理想的方法吗?我想为Book对象本身添加更多功能,以允许直接使用已加载的mongo数据。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...