При сохранении рецепта вы можете использовать блок «попробуй / исключить». Примерно так:
try:
recipe.save()
except DuplicateKeyError:
return render_template('error.html')
Очевидно, что здесь не хватает многих деталей, но это общая идея.
Я бы просто использовал более традиционный подход к отношениям внешнего ключа между комментариями и тем, к чему они привязаны.
UNIVERSITY
UniversityID // assuming primary key
COMMENTS
CommentID // assuming primary key
TypeID // Foreign Key
Type // Name of the table where the foreign key is found (ie, University)
Мне это кажется немного чище. Некоторые высказывания об использовании внешнего ключа другой таблицы в качестве первичного ключа для ваших комментариев не казались правильными.
If you use a UUID, it's hard to know what table it came from. If you only ever want to look from the entity down to the comments, as in your query, it'll work alright. If you want to look at a comment and find out what it was on, you'll have to look at all possible tables (universities, buildings, etc.) to find out.
One possibility which enables you to use simple sequential integers for keys of your base entities (which is often desirable for readability, index fragmentation, etc.) is to make the key of your comments table contain two columns. One is the name of the table the comment applies to. The second is the key of that table. This is similar to the approach Bryan M. suggests, though note that you won't be able to actually define foreign keys from the comments table to all possible parents. Your queries will work both ways round if necessary, and you don't need to worry about UUIDs, as the combination of table name + ID will be unique across the database.
Ну, поскольку никто, похоже, не хочет отвечать, думаю, я просто буду придерживаться своего метода. Однако я все еще готов принять другие предложения.