class StudentResource(resources.ModelResource): first_name = Field(attribute='first_name', column_name='first_name') last_name = Field(attribute='last_name', column_name='last_name') guardian_email = Field(attribute='guardian_email', column_name='guardian_email') birthday = Field(attribute='birthday', column_name='birthday') gender = Field(attribute='gender', column_name='gender') school_name = Field(attribute='school_name', column_name='school_name') school_type = Field(attribute='school_type', column_name='school_type') photo_release = Field(attribute='photo_release', column_name='photo_release') consent = Field(attribute='consent', column_name='consent') def import_obj(self, obj, data, dry_run): guardian_email = data.get('guardian_email') obj.first_name = data.get('first_name') obj.last_name = data.get('last_name') obj.birthday = datetime.strptime(data.get('birthday', ''), '%m/%d/%Y') obj.gender = data.get('gender', '') obj.school_name = data.get('school_name', '') obj.school_type = data.get('school_type', '') obj.photo_release = str_to_bool(data.get('photo_release', '')) obj.consent = str_to_bool(data.get('consent', '')) obj.is_active = True try: obj.guardian = Guardian.objects.get(user__email=guardian_email) except Guardian.DoesNotExist: raise ImportError( u'guardian with email {} not found'.format(guardian_email)) if not dry_run: obj.save() class Meta: model = Student import_id_fields = ('first_name', 'last_name') fields = ('first_name', 'last_name')
class TeacherManagementResource(resources.ModelResource): username = Field(attribute="user__username", column_name="用户名") name = Field(attribute="user__name", column_name="中文名") commission = Field(attribute="commission", column_name="当前佣金余额") total_commission = Field(attribute="total_commission", column_name="当前总佣金") scale_factor = Field(attribute="scale_factor", column_name="佣金配置") added_datetime = Field(attribute="added_datetime", column_name="创建时间") updated_datetime = Field(attribute="updated_datetime", column_name="更新时间") class Meta: model = TeacherManagement fields = ['id', 'username', 'name', 'commission', 'total_commission', 'scale_factor', 'added_datetime', 'updated_datetime'] export_order = ['id', 'username', 'name', 'commission', 'total_commission', 'scale_factor', 'added_datetime', 'updated_datetime']
class ProductResource(resources.ModelResource): category = Field(attribute='category', column_name='category', widget=ForeignKeyWidget(ProductCategory, 'pk')) class Meta: model = Product skip_unchanged = True report_skipped = True import_id_fields = ('reference', ) exclude = ('id', ) def before_import_row(self, row, **kwargs): # Get or create nested models category_model, _created = ProductCategory.objects.get_or_create( reference=row.get('category'), ) row['category'] = category_model.id
class CourseResource(ModelResource): class Meta: model = Course exclude = ('created_at', 'reg_number', 'inner_id') id = Field(attribute='id', column_name='id', widget=UUIDWidget()) rmu = fields.Field(column_name='manajemen_unit', attribute='rmu', widget=widgets.ForeignKeyWidget(ManagementUnit, 'code')) course_type = fields.Field(column_name='jenis_mk', attribute='course_type', widget=widgets.ForeignKeyWidget( CourseType, 'alias')) course_group = fields.Field(column_name='kelompok_mk', attribute='course_group', widget=widgets.ForeignKeyWidget( CourseGroup, 'alias'))
class SundaySermonResource(resources.ModelResource): servant_name = Field(attribute='servant_names', column_name="Servants") class Meta: model = Service exclude = ('slug', 'id', 'servants', 'services_of_week', 'categories', 'description') export_order = ('service_date', 'servant_name', 'note') def get_queryset(self): return self._meta.model.objects.filter( categories__name__in=SERMON_GROUP).order_by('service_date') def dehydrate_servant_name(self, service): servants = service.servants.all() servant_names = [servant.name for servant in servants] return ','.join(servant_names)
class DiretoriaResource(ModelResource): campus = Field(column_name='campus', attribute='campus', widget=ForeignKeyWidget(Campus, 'sigla')) class Meta: model = Diretoria import_id_fields = ( 'campus', 'sigla', ) fields = ( 'campus', 'sigla', 'descricao', 'active', )
class BreakfastResource(resources.ModelResource): user = Field(attribute="user", widget=ForeignKeyWidget(model=get_user_model(), field="name")) bread = Field(attribute="bread", widget=ForeignKeyWidget(model=Bread, field="name")) base = Field(attribute="base", widget=ForeignKeyWidget(model=Base, field="name")) ingredient1 = Field(attribute="ingredient1", widget=ForeignKeyWidget(model=Ingredient, field="name")) ingredient2 = Field(attribute="ingredient2", widget=ForeignKeyWidget(model=Ingredient, field="name")) drink = Field(attribute="drink", widget=ForeignKeyWidget(model=Drink, field="name")) class Meta: model = Breakfast fields = ("id", "user", "bread", "base", "ingredient1", "ingredient2", "drink") export_order = fields
class TeacherResource(resources.ModelResource): first_name = Field(attribute='first_name', column_name='First Name') last_name = Field(attribute='last_name', column_name='Last Name') profile_picture = Field(attribute='profile_picture', column_name='Profile picture') email_address = Field(attribute='email_address', column_name='Email Address') phone_number = Field(attribute='phone_number', column_name='Phone Number') room_number = Field(attribute='room_number', column_name='Room Number') subjects = Field(attribute='subjects', column_name='Subjects taught', widget=ManyToManyWidget(Subject, field='name')) def before_import_row(self, row, **kwargs): new_subjects = '' splitted = row['Subjects taught'].split(',') if row['Profile picture'] != '': row['Profile picture'] = row['Profile picture'].upper() for s in splitted: subject = s.strip().capitalize() if subject != '': if subject == 'Maths': subject = 'Mathematics' num_results = Subject.objects.filter(name=subject).count() if num_results < 1: sub = Subject(name=subject) sub.save() new_subjects += subject + ', ' new_subjects = new_subjects.rstrip(',') row['Subjects taught'] = new_subjects def skip_row(self, instance, original): if instance.first_name == '': return True return super(TeacherResource, self).skip_row(instance, original) class Meta: model = Teacher skip_unchanged = True report_skipped = True raise_errors = False import_id_fields = ('email_address', )
class ContentResource(resources.ModelResource): id = Field(attribute='id', column_name='pk1') handle = Field(attribute='handle', column_name='cnthndlr_handle') date_start = Field(attribute='date_start', column_name='start_date') date_end = Field(attribute='date_end', column_name='end_date') date_created = Field(attribute='date_created', column_name='dtcreated') date_modified = Field(attribute='date_modified', column_name='dtmodified') class Meta: model = Content skip_unchanged = True report_skipped = True
class IntentionSource(resources.ModelResource): """意向池导入导出resources""" id = Field( column_name="编号", attribute='id', default=None ) salesman = Field( column_name="销售", attribute='salesman', default=None ) intention_client = Field( column_name="意向名称", attribute='intention_client' ) contact_name = Field( column_name="联系人姓名", attribute='contact_name' ) contact_number = Field( column_name="电话(或微信)", attribute='contact_number' ) intention_progress = Field( column_name="意向进展", attribute='follow_situations' ) remark = Field( column_name="备注", attribute='remark' ) fill_date = Field( column_name="填写日期", attribute='fill_date', default=None, widget=DateWidget(format='%Y-%m-%d') ) class Meta: model = Intentions fields = ( 'id', 'salesman', 'intention_client', 'contact_name', 'contact_number', 'intention_progress', 'remark', 'fill_date' ) export_order = fields skip_unchanged = True import_id_fields = ['id'] def get_export_headers(self): export_headers = [u'编号', u'销售', u'意向客户', u'合同号', u'电话(或微信)', u'意向进展', u'备注', u'填写日期'] return export_headers
class AnswerHHMembersFromKoboResource(resources.ModelResource): answer_id = Field(attribute='answer_id', column_name='answer_id') gender = Field(attribute='gender', column_name='gender') birth = Field(attribute='birth', column_name='birth') ethnicity = Field(attribute='ethnicity', column_name='ethnicity') head = Field(attribute='head', column_name='head') seq = Field(attribute='seq', column_name='seq') last_update = Field(attribute='last_update', column_name='last_update') class Meta: model = AnswerHHMembers import_id_fields = ('answer_id', 'seq') def before_import_row(self, row, **kwargs): row["last_update"] = datetime.now()
class AthleteResource(resources.ModelResource): """ Example CSV: name,club Joe Morrow,OUCCC Tom Wood,OUCCC """ club = Field( column_name="club", attribute="club", widget=ForeignKeyWidget(Club, "name") ) # Fill id column def before_import(self, dataset, using_transactions, dry_run, **kwargs): print("Before import") dataset.insert_col(0, col=["",] * dataset.height, header="id") def before_import_row(self, row, row_number=None, **kwargs): print("Before row import") if not "power_of_10" in row.keys() or row["power_of_10"] == "": name = None club = None if "club" in row.keys(): club = row["club"] if "name" in row.keys(): name = row["name"] if name: row["power_of_10"] = lookup_po10(name, club) print(row) def get_instance(self, instance_loader, row): return False class Meta: # fields model = Athlete fields = ( "name", "power_of_10", "club", )
class DiscussionResource(resources.ModelResource): id = Field(attribute='id', column_name='pk1') date_posted = Field(attribute='date_posted', column_name='posted_date') date_modified = Field(attribute='date_modified', column_name='last_edit_date') message_text = Field(attribute='message_text', column_name='msg_text') message = Field(attribute='message', column_name='msgmain_pk1') conference = Field(attribute='conference', column_name='confmain_pk1') forum = Field(attribute='forum', column_name='forummain_pk1') course = Field(attribute='course', column_name='crsmain_pk1') deid = Field(attribute='deid', column_name='De-id') fields = ('id', 'date_posted =', 'date_modified', 'subject', 'message_text ', 'message', 'conference', 'forum', 'name', 'course', 'deid', 'user_role') export_order = ('id', 'date_posted =', 'date_modified', 'subject', 'message_text ', 'message', 'conference', 'forum', 'name', 'course', 'deid', 'user_role') class Meta: model = Discussion skip_unchanged = True report_skipped = True
class BankRecordResource(resources.ModelResource): date_processed = Field(attribute='date_processed', column_name='Date Processed') date_transaction = Field(attribute='date_transaction', column_name='Date of Transaction') unique_id = Field(attribute='unique_id', column_name='Unique Id') tran_type = Field(attribute='tran_type', column_name='Tran Type') reference = Field(attribute='reference', column_name='Reference') description = Field(attribute='description', column_name='Description') amount = Field(attribute='amount', column_name='Amount') class Meta: model = BankRecord import_id_fields = ('unique_id', ) skip_unchanged = True report_skipped = False
class PaymentResource(resources.ModelResource): id = Field(column_name="编号", attribute='id', default=None) payment_number = Field(column_name="到账编号", attribute='payment_number', default=None) contract_number = Field(column_name="合同号", attribute='contract_number', default=None) receive_value = Field(column_name="到账金额", attribute='receive_value', default=None) wait_invoices = Field(column_name="待开票额", attribute='wait_invoices', default=None) receive_date = Field( column_name="到账时间", attribute='receive_date', widget=DateWidget(format='%Y-%m-%d'), default=None, ) record_number = Field( column_name="业务流编号", attribute='record_number', ) class Meta: model = Payment fields = ('id', 'payment_number', 'contract_number', 'receive_value', 'wait_invoices', 'receive_date', 'record_number') export_order = ( 'id', 'payment_number', 'contract_number', 'receive_value', 'wait_invoices', 'receive_date', ) skip_unchanged = True import_id_fields = ['id'] def dehydrate_contract_number(self, payment): contract_number = payment.record_number.contract_number.contract_number return contract_number def get_export_headers(self): export_headers = ["编号", "到款编号", "合同号", "到账金额", "待开票额", "到账时间", '业务流编号'] return export_headers
class CategoryResource(resources.ModelResource): servants = Field(attribute='servants', column_name='Servants') class Meta: model = Category exclude = ('slug', 'id') export_order = ('name', 'description', 'servants') def get_queryset(self): return self._meta.model.objects.order_by('id') def dehydrate_servants(self, record): services = Service.objects.filter(categories__name=record.name).all() servants = set([ servant.name for service in services for servant in service.servants.all() ]) return ','.join(servants) if servants else None
class UserResource(ModelResource): class Meta: model = get_user_model() fields = ('id', 'first_name', 'username', 'email', 'is_active', 'is_student', 'is_teacher', 'is_employee', 'is_management', 'is_matriculant', 'is_applicant') id = Field(attribute='id', column_name='id', widget=UUIDWidget()) first_name = Field(column_name='full_name', attribute='first_name') email = Field(column_name='email', attribute='email') new_password = Field(column_name='new_password', attribute='new_password') confirm_password = Field(column_name='confirm_password', attribute='confirm_password') password = Field(column_name='password', attribute='password', readonly=True) groups = fields.Field(column_name='group', attribute='groups', widget=widgets.ManyToManyWidget(Group, separator=',', field='name')) def check_confirm_password(self, psw, confirm): return psw == confirm def get_or_init_instance(self, instance_loader, row): """ Either fetches an already existing user or initializes a new one. """ new_password = row.pop('new_password') confirm_password = row.pop('confirm_password') if new_password != confirm_password: raise ValueError(_("Password doesn't match !")) instance = self.get_instance(instance_loader, row) if instance: instance.new_password = new_password instance.confirm_password = confirm_password return (instance, False) else: new_instance = self.init_instance(row) new_instance.new_password = new_password new_instance.confirm_password = confirm_password return (new_instance, True) def before_save_instance(self, instance, using_transactions, dry_run): """ Set password if new one is available """ if instance.new_password not in ['', None]: validate_password(instance.new_password, instance) instance.set_password(instance.new_password)
class UserResource(CleanModelResource): id = Field(attribute='id', column_name='ID') name = Field(attribute='name', column_name='Nome') email = Field(attribute='email', column_name='Email') phone = Field(attribute='phone', column_name='Telefone') address = Field(column_name='Endereço') city_state = Field(column_name='Cidade/Estado') causes = Field(column_name='Causas') joined_date = Field(attribute='joined_date', column_name='Data do cadastro') class Meta: model = User fields = ( 'id', 'name', 'email', 'phone', 'address', 'city_state', 'causes', 'joined_date', ) def dehydrate_causes(self, user): if user.profile: return ", ".join([c.name for c in user.profile.causes.all()]) def dehydrate_address(self, user): if user.profile is not None: if isinstance(user.profile.address, GoogleAddress): return user.profile.address.address_line if isinstance(user.profile.address, SimpleAddress): return user.profile.address.street + ', ' + user.profile.address.number + ' - ' + user.profile.address.neighbourhood + ' - ' + user.profile.address.city def dehydrate_city_state(self, user): if user.profile is not None: if isinstance(user.profile.address, GoogleAddress): return user.profile.address.city_state if isinstance(user.profile.address, SimpleAddress): return user.profile.address.city
class Meta: model = Equipment split_tag = Field() def dehydrate_split_tag(self, equipment): return '%s-%s' % (equipment.equipment_type, equipment.inventory_number) fields = ( 'inventory_tag', 'manufacturer', 'description', 'model_number', 'serial_number', 'condition_as_recieved', 'calibration_date', 'due_date', 'calibration_frequency', 'status', 'location', 'assignee', 'calibrated_by', )
class AppointmentResource(ModelResource): offstudy_datetime = Field(column_name="offstudy_datetime") def dehydrate_offstudy(self, obj): visit_schedule = site_visit_schedules.get_visit_schedule( visit_schedule_name=obj.visit_schedule_name) schedule = visit_schedule.schedules.get(obj.schedule_name) try: off_schedule_obj = schedule.offschedule_model_cls.objects.get( subject_identifier=obj.subject_identifier, report_datetime__lte=obj.appt_datetime, ) except ObjectDoesNotExist: return None return off_schedule_obj.offschedule_datetime class Meta: model = Appointment
class ResultsResource(resources.ModelResource): racer = Field(column_name='ustsa_num', attribute='ustsa_num', widget=ForeignKeyWidget(Racer, 'ustsa_num')) class Meta: model = RacerResult def before_import(self, dataset, using_transactions, dry_run, **kwargs): try: Race.objects.get(id=dataset['race'][1]) except: print("the race doesn't exist") def after_import(self, dataset, result, using_transactions, dry_run, **kwargs): race = Race.objects.get(id=dataset['race'][1]) Race.race_points.set_race_points(race.id) Race.race_points.calculate_race_penalty(race.id)
class DataElementExport(resources.ModelResource): code= Field(attribute='code', column_name='Element Code') name = Field(attribute='name', column_name='Element Name') shortname = Field(attribute='shortname', column_name='Short Name') description = Field(attribute='description', column_name='Description') measuremethod = Field(attribute='measuremethod', column_name='Measure Factor') aggregation_type = Field(attribute='aggregation_type', column_name='Type of Aggregation') class Meta: model = StgDataElement skip_unchanged = False report_skipped = False fields = ('code','name', 'location_name', 'shortname','description', 'measuremethod','aggregation_type')
class UpdateResource(resources.ModelResource): def before_import(self, dataset, using_transactions, dry_run, **kwargs): temp = dataset.headers dataset.insert(0, temp) dataset.headers = ['sku', 'upload_quantity'] dataset.insert_col(0, col=[ "", ] * dataset.height, header="id") category = Field(attribute='category', column_name='category') name = Field(attribute='name', column_name='Name') group_name = Field(attribute='group_name', column_name='Set') foil = Field(attribute='printing', column_name='Foil') condition = Field(attribute='condition', column_name='Condition') language = Field(attribute='language', column_name='Language') upload_date = Field(attribute='upload_date', column_name='upload date') upload_status = Field(attribute='upload_status', column_name='upload status') class Meta: model = Upload exclude = ('upload_price', )
class UserStoryResource(resources.ModelResource): type = Field(attribute="type", widget=ForeignKeyWidget(model=UserStoryType, field="name")) development_user = Field(attribute="development_user", widget=ForeignKeyWidget(model=get_user_model(), field="username")) validation_user = Field(attribute="validation_user", widget=ForeignKeyWidget(model=get_user_model(), field="username")) support_user = Field(attribute="support_user", widget=ForeignKeyWidget(model=get_user_model(), field="username")) tags = Field(attribute="tags", widget=TagsWidget()) creation_user = Field( attribute="creation_user", widget=ForeignKeyWidget(model=get_user_model(), field="username"), default=get_current_authenticated_user, ) class Meta: model = UserStory fields = ( "id", "name", "type", "epic", "sprint", "functional_description", "technical_description", "start_date", "end_date", "validated", "planned_effort", "priority", "development_user", "development_comments", "validation_user", "validation_comments", "support_user", "support_comments", "cvs_reference", "risk_level", "risk_comments", "use_migrations", "deployment_notes", "tags", "creation_user", ) export_order = fields
class PriceFromKoboResource(resources.ModelResource): dataset_uuid = Field(attribute='dataset_uuid', column_name='dataset_uuid') gs = Field(attribute='gs', column_name='gs') have = Field(attribute='have', column_name='have') necessary =Field(attribute='necessary', column_name='necessary') quantity = Field(attribute='quantity', column_name='quantity') last_update = Field(attribute='last_update', column_name='last_update') class Meta: model = Price import_id_fields = ('dataset_uuid', 'gs', 'village',) def before_import_row(self, row, **kwargs): row["dataset_uuid"] = KoboData.objects.get(dataset_uuid=row["dataset_uuid"]) row["last_update"] = datetime.now()
class AnswerGSFromKoboResource(resources.ModelResource): # id = answer_id = Field(attribute='answer_id', column_name='answer_id') gs = Field(attribute='gs', column_name='gs') have = Field(attribute='have', column_name='have') necessary =Field(attribute='necessary', column_name='necessary') quantity = Field(attribute='quantity', column_name='quantity') last_update = Field(attribute='last_update', column_name='last_update') class Meta: model = AnswerGS import_id_fields = ('answer_id', 'gs', ) def before_import_row(self, row, **kwargs): row["last_update"] = datetime.now()
class CustomUserResource(resources.ModelResource): # symptoms = Field() # answers = Field() covid_status = Field() class Meta: model = CustomUser fields = ('name', 'email', 'phone', 'username', 'address', 'last_login', 'date_joined', 'age', 'dob', 'gender', 'covid_status') export_order = ('name', 'email', 'phone', 'username', 'address', 'last_login', 'date_joined', 'age', 'dob', 'gender', 'covid_status') # symptoms = Field( # attribute = 'symptoms', # widget= ManyToManyWidget(UserQuarantineSymptomsData, 'id') # ) def dehydrate_covid_status(self, obj): return obj.covid_status()
class Prg_base_resource(resources.ModelResource): contract = Field(column_name="合同编号", attribute="contract", widget=ForeignKeyWidget(Contract, 'name')) def __init__(self): super(Prg_base_resource, self).__init__() # 获取所以字段的verbose_name并存放在字典 field_list = Prgsheet._meta.fields self.vname_dict = {} for i in field_list: self.vname_dict[i.name] = i.verbose_name def get_export_fields(self): fields = self.get_fields() for field in fields: field_name = self.get_field_name(field) # 如果我们设置过verbose_name,则将column_name替换为verbose_name。否则维持原有的字段名 if field_name in self.vname_dict.keys(): field.column_name = self.vname_dict[field_name] return fields
class PaymentResource(FriendlyExportMixin, resources.ModelResource): payer_name = Field() payer_name.column_name = _("Paid by") def dehydrate_payer_name(self, payment): """ Get the representation of the person that made the payment via the generic relation. """ return str(payment.content_object) class Meta: model = Payment fields = [ "receipt_id", "amount", "payment_date", "notes", "payer_name", ] export_order = fields
class ClientResource(resources.ModelResource): email = Field(attribute='email', widget=ManyToManyWidget(Email, separator=', ', field='email_address')) paypal_email = Field(attribute='paypal_email', widget=ManyToManyWidget(Email, separator=', ', field='paypal_email_address')) website_url = Field(attribute='website_url', widget=ManyToManyWidget(Email, separator=', ', field='url')) training_url = Field(attribute='training_url', widget=ManyToManyWidget(Email, separator=', ', field='url')) type_of_task_request = Field(attribute='type_of_task_request', widget=ManyToManyWidget(Email, separator=', ', field='name_of_task')) channel_of_communications = Field(attribute='channel_of_communications', widget=ManyToManyWidget( Email, separator=', ', field='name_of_channel')) class Meta: model = Clients fields = ('username__username', 'full_name', 'company_name', 'date_signed_up', 'client_control_number', 'referred_by', 'lead_source', 'assigned_va__name', 'assigned_pm__project_manager', 'task_enroute', 'type_of_task', 'internal_folder_link_1', 'internal_folder_link_2', 'internal_folder_link_3', 'phone_number', 'company_category', 'status', 'email', 'paypal_email', 'website_url', 'training_url', 'type_of_task_request', 'channel_of_communications') export_order = ('username__username', 'full_name', 'company_name', 'date_signed_up', 'client_control_number', 'referred_by', 'lead_source', 'assigned_va__name', 'assigned_pm__project_manager', 'task_enroute', 'type_of_task', 'internal_folder_link_1', 'internal_folder_link_2', 'internal_folder_link_3', 'phone_number', 'company_category', 'status', 'email', 'paypal_email', 'website_url', 'training_url', 'type_of_task_request', 'channel_of_communications')