Home > Back-end >  Python - Is it better to pass an SQLAlchemy model, or an id no. to query again?
Python - Is it better to pass an SQLAlchemy model, or an id no. to query again?

Time:05-18

Example code:

def primary_function(object_id):
    some_object = SomeObject.query.get(object_id)
    # Do stuff here
    secondary_function(unknown_parameter)


def secondary_function(unknown_parameter):
    # Do more stuff here

Both functions need access to some_object. Is it more efficient to have unknown_parameter be the object itself, or would it be better to have it as object_id, and then call SomeObject.query.get(object_id) a second time?

I didn't see anything about this in the documentation (though I suppose I could have missed something), and all the other questions here that I could find were for other languages and had mixed answers.

CodePudding user response:

In general, when you're using the ORM, you'd do the second, but as a method:

class Foo(Model):
    def bar(self, param):
        ... work on self ...

If you pass in the object_id, that can be useful for bulk operation, but consider if passing in queryset instead is more appropriate for your use case:

def bar1(object_id, param):
    queryset = session.query(Foo).where(id=object_id)
    bar2(queryset, param)

def bar2(queryset, param): 
    queryset.update(...)

That way, you can use the same method (bar2) when updating both single row or when the queryset has more complex WHERE clause.

  • Related