ponyorm / pony

Pony Object Relational Mapper
Apache License 2.0
3.58k stars 242 forks source link

Many to many relation without duplicate #678

Closed ClementineSz closed 1 year ago

ClementineSz commented 1 year ago

Hey ! I'm trying to create this Many to many relationships. But how can I make sure that i'm not duplicating hashtags in the table hashtag and i have all the relationship on my liaison table PostHashtag. If someone can help ! 🙏

class Post(db.Entity):
    id = PrimaryKey(int, auto=True)
    ig_post_id = Required(LongStr)
    hashtags = Set('Hashtag')

class Hashtag(db.Entity):
    id = PrimaryKey(int, auto=True)
    posts = Set(Post)
    hashtag = Required(str)
@db_session
def insert_hashtags_db(p):
    print(f'Inserting hashtags {p["id"]}')
    if Post.exists(ig_post_id=p['id']):
        if not Hashtag.exists(hashtag=p['hashtags']):
            h1 = Hashtag(posts=Post.get(ig_post_id=p['id']), hashtag=p['hashtags'])

Like i want to have hashtag : id , name 1, hash1 2, hash2 3, hash3

post : 1, postA, [hash1, hash2, hash3] 2, postB, [hash1, hash3]

Hashtag_post 1, postA, hash1 2, postB, hash1 3, postA, hash2