Rus925
Rus925

Reputation: 408

Making SQLAlchemy records from a list

Fairly new to Python and very new to SQLAlchemy. Wondering how I can use a for loop to make multiple SQLAlchemy records from a list. Here's a very simplified version of what I have.

class ListItem(Base): 
    __tablename__ = list_items
    id = Column(Integer, primary_key=True)
    item = Column(String(50))

def list_to_ListItem(list_of_things): 
    for thing in list_of_things: 
        listitem = ListItem()
        listitem.item = thing

I haven't yet run this because there's actually a lot more to my code that still needs to be worked out, but I'm under the impression that, instead of creating a record in list_items for each thing in list_of_things, this will simply create one record assigned to listitem that it will overwrite with every iteration of the for loop.

So how do I do this? Like I said, I'm fairly new to Python, but I've heard something about factory functions that I don't understand but which, at least in name, sounds promising for this problem. Thanks in advance!

Upvotes: 0

Views: 174

Answers (1)

jkmacc
jkmacc

Reputation: 6427

List comprehension?

list_items = [ListItem(item=thing) for thing in list_of_things]

Upvotes: 2

Related Questions