How to get values of a model in flask?

0

I'm trying to get the values of a model in flask, I want to access the values of my model, not a " render_template "

record = MyModel.query.filter_by(id=222)

But with this I get an SQL query back.

The idea is to access as if it were a dictionary and get the values with get()

Any suggestions?

    
asked by afr 12.12.2017 в 01:02
source

1 answer

1

If I'm not wrong, filter_by returns an object that you can iterate, however, I see that what you really want is a specific record so the best thing you can do is use get :

record = MyModel.query.get(id=222)

Then you can access the fields that you have defined in your model:

record.campoX
record.campoY
# ...

On the other hand, if your query is used to filter several records then you can do:

records = MyModel.query.filter_by(...)
for record in records:
    record.campoX
    record.campoY
    # ...

I do not see any reason to want to access the fields using dictionaries but, in fact, you could do it using __dict__ (as mentioned by @amenadiel):

record.__dict__.get('campoX')

More code and less sense.

    
answered by 17.02.2018 в 17:33