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

553 Views Asked by At

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

There are 1 best solutions below

2
On BEST ANSWER

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)