I have an entity with more than 25 properties. Out of these 25, 15 properties are displayed in the frontend table. These table will allow to do a sorting (both ASC & DESC) on each properties.
To handle this in backend, I'm checking the order type and writing query on each property for both ASC and DESC order. To handle the 15 records sorting I'm having a lots of line code which looks similar. Only difference is the order type.
Code looks like this:
@classmethod
def retrieve(cls, order, limit, offset):
if order == '-property_1':
results = cls.query(ancestor=parent).order(-cls.property_1).fetch(limit, offset=offset)
elif order == 'property_1':
results = cls.query(ancestor=parent).order(cls.property_1).fetch(limit, offset=offset)
.
.
.
.
elif order == '-property_15':
results = cls.query(ancestor=parent).order(-cls.property_15).fetch(limit, offset=offset)
elif order == 'property_15':
results = cls.query(ancestor=parent).order(cls.property_15).fetch(limit, offset=offset)
And its creating 2 datastore index for each property.
- kind: EntityName
ancestor: yes
properties:
- name: property_1
- kind: EntityName
ancestor: yes
properties:
- name: property_1
direction: desc
My question here is Is there any better way to handle this case ?
If the parameters you're passing always match your property names then you can replace your if statements with something like:
desc = False
if order[0] == '-':
order = order[1:]
desc = True
query = cls.query(ancestor=parent)
order = getattr(cls, order)
if desc:
order = -order
query = query.order(order)
results = query.fetch(limit, offset=offset)