Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enhancement request: How to get an object by primary key when it is a composite key #7

Closed
paxet opened this issue Sep 7, 2018 · 3 comments

Comments

@paxet
Copy link
Contributor

paxet commented Sep 7, 2018

When using Composite primary keys for an entity and then entity.get_pk() it returns a tuple.
How to retrieve object from database with that tuple?

I'm seeking something like this:

# Define entity
MyEntity(db.Entity):
  a = Required(str)
  b = Required(str)
  PrimaryKey(a, b)

# Create and Save object to database
ent = MyEntity()
ent.a = 'Key1'
ent.b = 'Key2'
pony.orm.commit()

# Save reference
classname = ent.__class__.__name__
primary_key = ent.get_pk()

# Get from database by primary_key
ent2 = MyEntity[primary_key]

TypeError: Invalid count of attrs in OrgUnitClosure primary key (1 instead of 2)

@paxet paxet changed the title Enhancement reques: How to get an object by primary key when it is a composite key Enhancement request: How to get an object by primary key when it is a composite key Sep 10, 2018
@GittCatt
Copy link

Are you sure you've posted a correct example? The following works for me:

from pony.orm import *

db = Database()

class MyEntity(db.Entity):
    a = Required(str)
    b = Required(str)
    PrimaryKey(a, b)

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

ent = MyEntity(a='Key1', b='Key2')
commit()

primary_key = ent.get_pk()
>>> MyEntity[primary_key]
MyEntity['Key1','Key2']

@paxet
Copy link
Contributor Author

paxet commented Nov 14, 2018

My fault, sorry.
The tuple returned from get_pk() was getting converted to str to be stored in another table, a simple 'eval' solved it.

from pony.orm import *

db = Database()

class MyEntity(db.Entity):
    a = Required(str)
    b = Required(str)
    PrimaryKey(a, b)

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

with db_session():
    ent = MyEntity(a='Key1', b='Key2')
    primary_key = str(ent.get_pk())
    ent = MyEntity[eval(primary_key)]
>>> MyEntity[eval(primary_key)]
MyEntity['Key1', 'Key2']

@paxet paxet closed this as completed Nov 14, 2018
@sashaaero
Copy link
Member

sashaaero commented Nov 14, 2018

First of all I think this issue relates to pony itself, not pony-doc repository.
About composite keys - it was bug in Pony that we've fixed here. And will be released soon in Pony 0.7.7

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants