0

Basically, I've learned this far that coding something the right way means you shouldn't have to copy and paste a lot.. At least from what I've read.

I basically need to assign my Django model points based on a boolean statement. If True add points otherwise dont add points. The point values will change but for now I have them set as 1.

I can either copy/paste as many of these are I have to record scores for or I can see if there's an easier way, so ultimately thats my question, is there an easier way?

        scores_bool = {
            'spc': 1,
            'medical': 1,
            'photo_id': 1,
            'presolo_test': 1,
            'presolo_checkout': 1,
            'endorsement_solo': 1,
            'solo': 1,
            'dual_xc': 1,
            'inst_training': 1,
            'dual_night': 1,
            'tol_tower': 1,
            'solo_xc': 1,
            'solo_xc_150': 1,
            'checkride_prep': 1,
        }
        if ppl.spc:
            ppl.points += scores_bool['spc']
        if ppl.medical:
            ppl.points += scores_bool['medical']
        if ppl.photo_id:
            ppl.points += scores_bool['photo_id']
        if ppl.presolo_test:
            ppl.points += scores_bool['pre_solo_test']
        

So basically each ppl attribute has a True False statement, if true add the points to it...etc

Ideally I would loop through the scores_bool.keys() and say something like:

for i in scores_bool.keys():
if ppl.i: 
    ppl.points += scores_bool[i] 


Thankyou! 
Nick H
  • 205
  • 2
  • 9

2 Answers2

0

I think you are close, but while ppl.i won't work, getattr(ppl, i, None) will.

for i in scores_bool.keys():
if getattr(ppl, i, None): 
    ppl.points += scores_bool[i] 
rhurwitz
  • 2,557
  • 2
  • 10
  • 18
0

Use built-in getattr method.

for i in scores_bool.keys():
    if getattr(ppl, i): 
       ppl.points += scores_bool[i]

For more information about how to call method by its string name, read this

Rustam Garayev
  • 2,632
  • 1
  • 9
  • 13
  • With this you have to be sure that the instance has every attribute from `scores_bool.keys()`, otherwise AttributeError will be raised. As far as this statement is just a predicate passing fallback value of `None` will do the trick. – jetpack_guy Feb 05 '21 at 20:34