Disclaimer: These have been ages since I used SQLAlchemy, so this is more a hunch than anything.
It looks like you expect SQLAlchemy to magically take the string βbarβ and look at the corresponding tag for it when pasting into a many-to-many table. I expect this to be wrong because the field ("tag") is not a primary key.
Imagine a similar situation where your tag table is actually a comment, as well as with an identifier and a text field. You expect that you can add comments to a post with the same syntax e.comments = ['u'Foo', 'u'Bar'] that you used above, but you want it to just execute INSERT, do not check existing comments with the same content.
So this is probably what it does here, but it hits the uniqueness constraint of your tag name and fails, suggesting that you are trying to do the wrong thing.
How to fix it? Creating a primary key tags.tag is probably the right thing, but I donβt know how efficient it is or how SQLAlchemy handles this. Otherwise, try querying for Tag objects by name before assigning their entries. You may need to write a small utility function that takes a Unicode string and either returns an existing tag or creates a new one for you.
source share