1
1
2
- """ Create a batch of single use discount coupons from a CSV file.
2
+ """ Create/update a batch of discount coupons from a CSV file.
3
3
4
4
Parameters: <conference> <csv-file>
5
5
6
- Creates coupons based on the CSV file contents:
6
+ Creates/updates coupons based on the CSV file contents:
7
7
8
8
code - coupon code
9
9
max_usage - max. number of uses
14
14
15
15
Use --dry-run to test drive the script.
16
16
17
+ Existing coupon codes will get updated by the script. Indexing is by
18
+ code.
19
+
17
20
"""
18
21
import sys
19
22
import csv
@@ -54,9 +57,9 @@ def handle(self, *args, **options):
54
57
csv_filename = options ['csv' ]
55
58
56
59
# Get set of existing coupon codes
57
- all_codes = set ( c [ ' code' ] for c in Coupon . objects \
58
- . filter ( conference = conference . code ) \
59
- . values ( ' code' ))
60
+ all_codes = dict (( c . code , c )
61
+ for c in Coupon . objects \
62
+ . filter ( conference = conference . code ))
60
63
61
64
# Valid fares (conference fares only)
62
65
all_fares = cmodels .Fare .objects \
@@ -70,23 +73,24 @@ def handle(self, *args, **options):
70
73
with csv_file :
71
74
reader = csv .DictReader (csv_file )
72
75
for row in reader :
76
+ #print ('Row %r' % row)
73
77
code = row ['code' ].strip ()
74
- if not code :
78
+ if not code or code == '0' :
75
79
# Skip lines without code
76
80
continue
77
81
if code in all_codes :
78
- # Skip coupons which already exist
79
- print ('Coupon %r already exists - skipping' % code )
80
- continue
81
- c = Coupon (conference = conference )
82
- c .code = code
82
+ print ('Coupon %r already exists - updating' % code )
83
+ c = all_codes [code ]
84
+ else :
85
+ print ('New coupon %r will be created' % c .code )
86
+ c = Coupon (conference = conference )
87
+ c .code = code
83
88
c .max_usage = int (row .get ('max_usage' , 1 ))
84
89
c .items_per_usage = int (row .get ('items_per_usage' , 1 ))
85
90
c .value = row ['value' ]
86
91
c .description = row .get ('description' , '' )
87
92
if not self .dry_run :
88
93
c .save ()
89
- c .fares = all_fares .filter (
94
+ c .fares . set ( all_fares .filter (
90
95
code__in = [x .strip ()
91
- for x in row ['fares' ].split (',' )])
92
- print ('Coupond %r created' % c .code )
96
+ for x in row ['fares' ].split (',' )]))
0 commit comments