PonyORM orphaned items when clearing a set that defines one-to-many relation -


i have basic relation defined follows: db = database('sqlite', 'test_db.sqlite', create_db=true)

class woeid(db.entity):     woeid      = primarykey(int)     iso        = optional(str)     name       = required(str)     language   = optional(str)     place_type = required(str)     parent_id  = required(int)     trends     = set('trend')     ancestry   = optional(str)  class trend(db.entity):     woeid                = required(int)     events               = optional(str)     name                 = required(str)     promoted_content     = optional(str)     query                = required(str)     url                  = required(str)     location             = optional(woeid)  db.generate_mapping(create_tables=true)  

now, add items woeid.trends within function decorated @db_session. works expected. try update woeid.trends first reading object using

 location = woeid.get(woeid = some_woeid) 

later on issue

location.trends.clear() 

to delete old entries , add new items trends set.

in generated trends table after operation have items added, previous items (cleared set) not deleted, stay in database 'location' field nulled (they dereferenced guess).

how should perform operation outlined above read of orphaned items?

there 2 kinds of one-to-many relationships in ponyorm. first kind of relationship when 1 end of relationship set , other end of relationship required. in case when remove item collection item deleted. example can define 2 entities article , comment in following way:

class article(db.entity):     author = required(user)     text = required(str)     comments = set('comment')  class comment(db.entity):     author = required(user)     text = required(str)     article = required(article) 

in case, when perform article.comments.clear() comment deleted, because comment.article attribute required , comment cannot exist without article.

the other kind of relationship comment.article attribute defined optional:

class comment(db.entity):     author = required(user)     text = required(str)     article = optional(article) 

in case comment can exist without article, , when remove comment article.comments collection remains in database, comment.article attribute value set null.

you can find orphaned items executing following query:

select(c c in comment if c.article none) 

or, equivalently

comment.select(lambda c: c.article none) 

in cases may desirable define attribute optional, perform cascade delete on removing item collection. in order this, can specify cascade_delete option set attribute:

class article(db.entity):     author = required(user)     text = required(str)     comments = set('comment', cascade_delete=true)  class comment(db.entity):     author = required(user)     text = required(str)     article = optional(article) 

then if article.comments.clear() removed comments deleted database.


Comments