I’m a python newbie so I apologize in advance if this question has been asked before.
I am building out an application in GAE and need to generate a report that contains the values for a user-defined subset of fields.
For example, in my db model, CrashReport, I have the following fields:
- entry_type
- entry_date
- instance_id
- build_id
- crash_text
- machine_info
I present a user with the above list as a checkbox group from which they select. Whichever fields the user selects, I then create a report showing all the values in the datastore, but only for the fields that they selected. For example, if from the above list, the user selects the build_id and crash_text fields, the output might look like this:
build_id crash_text
0.8.2 blown gasket
0.8.2 flat tire
0.8.1 crack
…
So the question is, how exactly do I only access the values for the fields which the user has defined?
Given a model instance
miand an attribute namean,getattr(mi, an)will fetch the value of attributeanfor objectmi. It will raiseAttributeErrorif objectmihas no attribute by that name; if you want to avoid this, try e.g.getattr(mi, an, None).So if you have a list of attribute names
la,gives you a list of the values of the various attributes whose names are in
lafor a given instancemi.If you also have a list of instances
li, and want a list of lists (one outer list per instance, each with all the attribute values),And so forth. These are all general Python concepts and operations and they apply to instances of models that you have fetched from the datastore, no less (and no more) than to any other Python objects.