(The process should be like this and not like any other!) There is an Object in the database with fields t1, t2, t3, t4, t5 . Each of them is a digital IntegerField. The default is 0 default=0 . There is a number in the pattern (say х ), which is different depending on t 1, t2, t3, t4, t5 . Namely, when they are all equal to 0, then х=0 , but if one of them takes any other number, then х changes to a number equal to the number of non-zero values ​​:) example:

 t1=0, t2=1, t3=0, t4=2, t5=0 =>>> x=2 (т.к. t2, t4 не равные 0). 

Question: how to describe it in a view and pass it to a template? Option with listing if / else of all options ... well, excuse me ...

    3 answers 3

     t = (t1, t2, t3, t4, t5) # используем кортеж для удобства работы, можно использовать и список 

    We write the algorithm "in the forehead" (as in the description):

     x = 0 for item in t: if item != 0: x += 1 print(x) 

    Everything is good, but 4 lines is too much. You can use the generators: create a list of the original - from elements that are not equal to zero, and take its length

     x = len(list(item for item in t if item != 0)) 

    a similar option - if we use not the generator, but the filter:

     x = len(list(filter(lambda x: x != 0, t))) # в python3 функция filter возвращает итератор - поэтому требуется преобразование в список, # в python2 работает и len(filter(lambda x: x != 0, t)) 

    or the reduce function (to briefly describe an assignment — it can run through the list and give either a sum or a product of elements):

     from functools import reduce # python 3 - функция reduce перемещена в functools x = reduce(lambda x, y: x + 1 if y != 0 else x, t) 

    For reference:

    A lambda function is an anonymous function. So usually declare small built-in functions. Before ":" the arguments are listed, after - the expression returned as a result. Ads:

     def check(x): return x > 0 

    and

     check = lambda x: x > 0 

    are equivalent

       value = 0 for attr in ['t1', 't2', 't3', 't4', 't5']: value += 1 if getattr(your_model, attr, 0) else 0 

      then you put the value into the content for the template. In essence, they are the same if / else, but in short.

        The filter function in Python 2.7 returns a list that satisfies the lambda functions . And we take its length.

         def counter: ... raw_list = [t1, t2, t3, t4, t5] list_of_not_null = filter(lambda x: x!=0, raw_list) ... return len(list_of_not_null) 
        • A good option, but it would be even better if you commented on the code at least a couple of lines - tutankhamun
        • I agree, the same error occurs: object of type 'filter' has no len () - FlatOMG
        • @FlatOMG What version of python are you using? filter guaranteed to return a list if you give it the correct input data. And len() applicable to any list. Watch carefully what you pass to filter . - Balas