问题描述
我有一个类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 (将#修改为@)