def apply_rules ( self , zone , salechannel ) :

rules = Rule. objects . filter ( active = True , level__active = True ) # never used

from service. calculate_price import get_apply_rules # why import here?

pks = get_apply_rules ( self , zone , salechannel )

ids = [ ]

sorted_rules = [ ]

if pks: # unnecessary, as get_apply_rules always returns a list

for pk in pks:

ids. append ( pk [ 2 ] [ "id" ] ) # what are list comprehensions

# original comment: "sort rules in order of usage" (i.e. pks)

if len ( ids ) > 0 : # unnecessary again; also "if ids:" is much simpler...

rules = Rule. objects . filter ( pk__in = ids ) # variables ids and pks are named idiotically

for pk in pks:

for rule in rules: # OH MY GOD! This is O(n^2)!

if rule. pk == pk [ 2 ] [ "id" ] : # OH. MY. GOD.

supp = Supplier. objects . get ( id = int ( pk [ 0 ] ) ) # int() is not necessary

art_code = pk [ 1 ]

if not supp. is_REDACTED :

art_code = supp. code + "_" + art_code

sorted_rules. append ( { 'art' :art_code , 'rule' :rule } )

break # how efficient!