def create(self, request, *args, **kwargs): bulk = isinstance(request.data, list) data = request.data if bulk else [request.data] # no more serializers that is not necessary for this creation # data should be a list of strings formatted_phone_nums = [] for phone_num_str in data: formatted_phone_num = format_phonenumber(phone_num_str, quiet=True) if not formatted_phone_num: continue formatted_phone_nums.append(formatted_phone_num) p_qs = Profile.objects.filter(phone_num__in=formatted_phone_nums).only('id', 'phone_num') records = [] # create for those not in the system phone_numm_profile_dict = dict((p.phone_numm, p) for p in p_qs) p_qs = list(p_qs) for formatted_phone_num in formatted_phone_nums: if formatted_phone_num not in phone_numm_profile_dict: p = Profile(phone_num=formatted_phone_num) p.save() p_qs.append(p) from_profile = get_object_or_404(Profile, user=self.request.user) for p in p_qs: records.append( PhoneContactRecord(from_profile=from_profile, to_profile=p, to_phone_num=p.phone_num) ) PhoneContactRecord.objects.filter(from_profile=from_profile).delete() PhoneContactRecord.objects.bulk_create(records) return Response(len(records), status=status.HTTP_201_CREATED)
def create(self, validated_data): occupations = validated_data.pop('occupations', None) tags = validated_data.pop('tags', None) # doing this for the time being phone_num = validated_data.pop('phone_num', None) if phone_num: validated_data['phone_num'] = format_phonenumber(phone_num) # only taking care of tags since other many2many relations will have extra through table to setup instance = super(ProfileSerializer, self).create(validated_data) if occupations: instance.occupations.add(*occupations) if tags: # this add will create those tag records not yet in the system # refer to taggit.managers.py#tags_to_create instance.tags.add(*tags) # since tags.add already done commit stuff # instance.save() return instance
def update(self, instance, validated_data): occupations = validated_data.pop('occupations', None) tags = validated_data.pop('tags', None) # doing this for the time being phone_num = validated_data.pop('phone_num', None) if phone_num: validated_data['phone_num'] = format_phonenumber(phone_num) # only taking care of tags since other many2many relations will have extra through table to setup instance = super(ProfileSerializer, self).update(instance, validated_data) if occupations != None: instance.occupations.set(*occupations) if tags != None: # since tags may set to empty [] # since tags.add already done the set intersection instance.tags.set(*tags) # since add just cater for appending situation not the removing situation # instance.tags.add(*tags) # since tags.add already done commit stuff # instance.save() return instance
def handle(self, *args, **options): wb = load_workbook(options['filepath'], use_iterators = True) ws = wb.worksheets[0] row_counter = 1 newly_created_counter, updated_counter = 0, 0 ''' phone_num gender city whatsup high_school college occupations(3 tops) tags(comma separated) 1234567890 male beijing aaa A中学 A大学 occupations1,occupations2 child1,child2, test 1234567891 shanghai bbb B中学 B大学 occupations child11, child21, test11 1234567892 female guangzhou ccc C中学 C大学 child22, test21 child22, test21 ''' name_occupation_dict = dict( (tag.name, tag) for tag in TreeTag.objects.get(slug='occupation-tag-root').get_descendants(include_self=False)) name_tag_dict = dict( (tag.name, tag) for tag in Tag.objects.all() ) name_high_school_dict = dict( (school.name, school) for school in School.objects.filter(type='high_school') ) name_college_dict = dict( (school.name, school) for school in School.objects.filter(type='college') ) for row in ws.iter_rows(row_offset=1): row_counter += 1 phone_num = row[0].value or '' gender_str = (row[1].value or '').strip() if gender_str: gender = 1 if gender_str.lower()=='male' else 0 else: gender = None defaults = { 'gender': gender, 'city': row[2].value or '', 'whatsup': row[3].value or '', } if row[4].value: defaults['high_school'] = name_high_school_dict.get(row[4].value.strip()) if row[5].value: defaults['college'] = name_college_dict.get(row[5].value.strip()) occupations_strs = re.split('[,锛� ]+', str( row[6].value or '' )) occupations = [ name_occupation_dict[tag_name] for tag_name in occupations_strs if tag_name in name_occupation_dict ] tag_strs = re.split('[,锛� ]+', str( row[7].value or '' ) ) tags = [] for tag_name in tag_strs: if tag_name in name_tag_dict: tags.append(name_tag_dict[tag_name]) else: if not tag_name: continue tag = Tag(name=tag_name) tag.save() tags.append(tag) name_tag_dict[tag_name] = tag print('phone_num', phone_num, 'defaults', defaults) try: phone_num = format_phonenumber(phone_num) profile, newly_created = Profile.objects.get_or_create(phone_num=phone_num, defaults=defaults) except Exception as e: raise CommandError('Line: %d encounter error: %s' % (row_counter, e, ) ) else: if newly_created: newly_created_counter += 1 else: for key, value in defaults.items(): setattr(profile, key, value) profile.save() updated_counter += 1 if occupations: profile.occupations.set(*occupations) if tag_strs: # if the tag is not in the system it would create a new one profile.tags.set(*tags) self.stdout.write('newly created: %d, updated: %d, total: %d' % (newly_created_counter, updated_counter, newly_created_counter+updated_counter, ) )