H
H
HeyAway2018-03-07 21:57:19
Python
HeyAway, 2018-03-07 21:57:19

How to access an attribute of an object dynamically?

Sorry, but I don't know what keywords to search for.
Let's say there is a code for getting data from the database and sorting it (schematically):

if sort_by == "date" : sort_by = Articles.created.desc()
Articles.select().order_by(sort_by).offset(offset).limit(limit)

Or:
if sort_by == "created" : sort_by = Articles.created.desc()
Articles.select().order_by(sort_by).offset(offset).limit(limit)

There are a lot of these "sort_by" values ​​and a rather long list is obtained. Add this to the fact that the application is full of sections and many models that work according to the same scenario: query -> get sorting options -> get data from the model. For each section the same code, one might say. Terrible.
So, once again I apologize, how to combine all this code into one function of the type:
sort_by - string
def get_all_data(Model, sort_by, offset, limit):
    try:
         sort_by = Model.%SORT_BY%.desc()
         return Model.select().order_by(sort_by).offset(offset).limit(limit)
    except:
         raise Exception("xxx")

These are probably the basics. True, I am not a programmer either, but it turned out that I had to deal with this area. There was a little experience in JS.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2018-03-07
@HeyAway

attr_name = 'created'
sort_by = getattr(Model, attr_name).desc()

But in general, for such tasks, it is better to use full-text search engines, such as Elasticsearch.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question