How to create an object in database only if the database is not there?

Anubhav Yadav anubhav.yadav at gmx.com
Thu Sep 7 10:20:50 EDT 2017


Hi, 

I am using `pony` orm to write a simple class as my model. Here is the class. 

```
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 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. If the course is already in the database, 
the orm should just return the same object. I have implemented the requirement as follows:

```
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)

    @staticmethod
    @db_session
    def new(title, url=None, thumbnail=None, processed=False):
        """Return a Course either new or from database"""
        course = select(c for c in Course if c.title == title)[:]
        if course:
            return course[0]
        return Course(title=title, url=url, thumbnail=thumbnail, processed=processed)

db.bind(provider='sqlite', filename=DB_PATH, create_db=True)
db.generate_mapping(create_tables=True)
```

Can there be a better method of doing that? Please let me know. 

Thanks. 

“ You are not born knowing everything.
  You go on learning” 

- Anubhav Yadav






More information about the Python-list mailing list