Hello,

This is the first time I try an ORM, and I chose SQLAlchemy, which is popular 
amongst pythonistas.

Since I am a complete beginner, here's my beginner's two cents question :

Suppose you have a very basic model like this (pseudo code) : 

User(firstname,lastname,nick,ManyToOne(city))
City(name)

Suppose I want to add a new user: 

user = User("John","Doe","jd", WhatToPutHere ?)

I whish I could write something like this :

user = User("John","Doe","jd", City("New Jersey"))

Where City will first fetch for a city named New Jersey in the database and 
return it if it exists, or create a new one (in the database) and return it.

So I thought maybe I could have a helper function like this : 

def city(name):
    return City.query.filter_by(name=name).first() or City(name=name)


and then : 

user = User("John","Doe","jd",city("New Jersey"))

But how can I be sure that the city of New Jersey will be inserted before the 
user in the database so that the new user row will get the proper city id ?

So I figured to rewrite the city helper function like this :

def city(name):
    theCity = City.query.filter_by(name=name).first()
    if not theCity :
       theCity = City(name=name)
       session.commit() # to be sure it will be inserted before the user
    return theCity

In the videostore example I saw an interresting use of the @classmethod 
decorator, which may be useful to define city as a static method of the City 
class.

I need your advice. Is this a good way to tackle to problem ? how does your 
code look like ?

Y.Chaouche


      

--

You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To post to this group, send email to sqlalch...@googlegroups.com.
To unsubscribe from this group, send email to 
sqlalchemy+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=.


Reply via email to