[Tutor] How to create an object in database only if the object is not already there?
Albert-Jan Roskam
sjeik_appie at hotmail.com
Mon Sep 11 10:12:41 EDT 2017
From: Tutor <tutor-bounces+sjeik_appie=hotmail.com at python.org> on behalf of GMX <anubhav.yadav at gmx.com>
Sent: Monday, September 11, 2017 9:38 AM
To: tutor at python.org
Subject: [Tutor] How to create an object in database only if the object is not already there?
<snip>
Now when I create a Course object like this:
>>> Course(title=‘A new course’)
An object is create in the database. I don’t want to have this behaviour, but what I want to be doing is create a Course object
and then only commit in the database if the course is not already available in the database.
===> I have no experience with Pony, but with Sqlalchemy one could do something like:
if not session.query(Course.title).filter_by(title=‘A new course’).first():
course = Course(title=‘A new course’)
Or perhaps you could set a primary key constraint on course title.
More information about the Tutor
mailing list