Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6173967
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T23:40:06+00:00 2026-05-23T23:40:06+00:00

I’d like to use relationship from sqlalchemy in my project. I test many-to-many on

  • 0

I’d like to use relationship from sqlalchemy in my project. I test many-to-many on simple code:

from sqlalchemy import Table, Column, Integer, String, Text, DateTime, ForeignKey, create_engine
from sqlalchemy.orm import relationship, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from datetime import datetime


engine = create_engine('sqlite:///m2m.sqlite', echo=True)

Base = declarative_base(engine)

post_tags = Table('post_tags', Base.metadata,
                Column('post_id', Integer, ForeignKey('blog_posts.id')),
                Column('tag_name', String, ForeignKey('blog_tags.name'))
)

class BlogPost(Base):
    __tablename__ = 'blog_posts'

    id = Column(Integer, primary_key=True, autoincrement=True)
    title = Column(String)
    content = Column(Text)
    created = Column(DateTime, default=datetime.now)   

    tags = relationship('BlogTag', secondary=post_tags, backref='blog_posts')

    def __init__(self, title, content, tags=None):
        self.title = title
        self.content = content
        if tags:
            self.tags = tags

    def __repr__(self):
        return '%d %s %s' % (self.id, self.title, self.content)

class BlogTag(Base):
    __tablename__ = 'blog_tags'

    name = Column(String, primary_key=True)

    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return '%s' % self.name

Base.metadata.create_all(engine)

Session = sessionmaker(engine)
dbs = Session()

post = BlogPost('1', '1111', [BlogTag('one'), BlogTag('two')])
dbs.add(post)
dbs.commit()

post = BlogPost('2', '222', [BlogTag('one'), BlogTag('newtag')])
dbs.add(post)
dbs.commit()

for x in dbs.query(BlogTag).all():
    print x

But I get exception on code:

post = BlogPost('2', '222', [BlogTag('one'), BlogTag('newtag')])
dbs.add(post)
dbs.commit()

How can I insert a new blog post to database if tags already exists in the table?


Thanks to everybody. I write follows code for BlogTag:

class BlogTag(Base):
    __tablename__ = 'blog_tags'

    name = Column(String, primary_key=True)

    @staticmethod
    def get(dbsession, name):
        obj = dbsession.query(BlogTag).filter(BlogTag.name == name).first()
        if not obj:
            obj = BlogTag(name)
        return obj

    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return '%s' % self.name

And I used them like below:

tags = [BlogTag.get(dbs, 'one'), BlogTag.get(dbs, 'two')]

post = BlogPost('1', '1111', tags)
dbs.add(post)
dbs.commit()

tags = [BlogTag.get(dbs, 'one'), BlogTag.get(dbs, 'newtag')]
post = BlogPost('2', '222', tags)
dbs.add(post)
dbs.commit()

I’m not sure that it is best way but it work 🙂

Can I get session from Base?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-23T23:40:07+00:00Added an answer on May 23, 2026 at 11:40 pm

    BlogPost('one') creates completely new object. You have to fetch existing tags from database instead.

    Also, in the example above you forgot to add a new tag to the database session.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

For some reason, after submitting a string like this Jack’s Spindle from a text
I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
I would like to count the length of a string with PHP. The string
I want to count how many characters a certain string has in PHP, but
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have just tried to save a simple *.rtf file with some websites and
I am trying to understand how to use SyndicationItem to display feed which is
I've got a string that has curly quotes in it. I'd like to replace
I would like to run a str_replace or preg_replace which looks for certain words
I am trying to render a haml file in a javascript response like so:

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.