[Tutor] How to create an object in database only if the object is not already there?

Alan Gauld alan.gauld at yahoo.co.uk
Mon Sep 11 10:26:57 EDT 2017


On 11/09/17 10:38, GMX wrote:
> I am using `pony` orm to write a simple class as my model.

pony is not a standard module (indeed I only heard about it
from your email) so you are probably best asking on the
pony support forum if such exists or via the author.


> from pony.orm import Database
> from pony.orm import Required, Optional
> from pony.orm import db_session
> from pony.orm import select, commit
> 
> DB_PATH = ‘db.sqlite’
> 
> db = Database()
> 
> class Course(db.Entity):
>     """
>     A class to represent a course
>     """
>     title = Required(str, unique=True)
>     url = Optional(str, unique=True)
>     thumbnail = Optional(str)
>     processed = Optional(bool, default=False)
> 
> db.bind(provider='sqlite', filename=DB_PATH, create_db=True)
> db.generate_mapping(create_tables=True)
> ```
> 
> 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 that's kind of what an ORM does. The whole point of using
an ORM is that it translates your objects into database
transactions.

> 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.

Thats very specific to your ORM. There probably are options
to do that, but you will need to ask the pony users.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list