How to create instance of a table entry but not added in ponyorm?

筅森魡賤 提交于 2019-12-13 03:29:58

问题


How can I use a create an instance of a table definition without inserting a row to the corresponding Table.

For example what I would like is:

from pony import orm
from pony.orm import Required
db = orm.Database()
class User(db.Entity):
    name = Required(str)
    address = Optional(str)

db.bind(provider='sqlite', filename=':memory:')
db.generate_mapping(create_tables=True)

bob = User(name='bob')

### CODE FROM HERE ON IS WRONG BUT SHOWCASES WHAT I WANT
# So far the database has not been modified
bob.add() # at this point bob is added
db.commit() # transaction is committed

Is the above possible? The reason I want this is that I want to use the class definition without adding items to the database. It's just a very easy clean way of making sure that Users everywhere (in this example) have the same attributes.

I was initially using pyDAL which I found very easy to set up tables but there I would have to define the tables and then also write the classes so I moved to ponyorm but it's unclear if I can achieve what I'd like.

thank you

UPDATE 1:

An example usecase for this is:

  • I'm scraping a website
  • I pull in "row" data
  • if address is not yet available
    • Create an instance of the User
    • Not add it just use the class as a container for the data
  • If the information is available
    • Create an instance and only if the record doesn't already exist add it

Basically I want to be able to use the Class as a container of the information without always having to add it to the database.


回答1:


PonyORM as ORM doesn't provide anything for this case. You still can use regular python dictionaries or classes.

users = {} # id: info

So when you accumulate (or whatever you doing) info you can create objects like this.

@db_session
def insert_users():
    for k, v in users.items():
        User(id=k, **v)


来源:https://stackoverflow.com/questions/53111070/how-to-create-instance-of-a-table-entry-but-not-added-in-ponyorm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!