class LeadResource(resources.ModelResource): id = fields.Field(attribute='id') first_name = fields.Field(attribute='first_name', column_name=_('First name')) last_name = fields.Field(attribute='last_name', column_name=_('Last name')) middle_name = fields.Field(attribute='middle_name', column_name=_('Middle name')) email = fields.Field(attribute='email', column_name=_('Email')) mobile = fields.Field(attribute='mobile', column_name=_('Mobile')) date_added = fields.Field(attribute='date_added', column_name=_('Date added')) messengers = fields.Field(attribute='messengers', column_name=_('Messengers'), widget=ManyToManyWidget(LeadMessenger, separator=';', field='name')) status = fields.Field(attribute='status', column_name=_('Status'), widget=ForeignKeyWidget(LeadStatus, 'name')) source = fields.Field(attribute='source', column_name=_('Source'), widget=ForeignKeyWidget(LeadSource, 'name')) course = fields.Field(attribute='course', column_name=_('Course'), widget=ForeignKeyWidget(LeadCourse, 'name')) consultant_name = fields.Field(attribute='consultant', column_name=_('Consultant name'), widget=ForeignKeyWidget(User, 'first_name')) consultant_surname = fields.Field(attribute='consultant', column_name=_('Consultant surname'), widget=ForeignKeyWidget(User, 'last_name')) action = fields.Field(attribute='action', column_name=_('Action')) action_date = fields.Field(attribute='action_date', column_name=_('Action date')) action_time = fields.Field(attribute='action_time', column_name=_('Action time')) comments = fields.Field(attribute='comments', column_name=_('Comments'), widget=ManyToManyWidget(CrmComment, separator=';', field='comment')) class Meta: model = Lead fields = ('id', 'first_name', 'middle_name', 'last_name', 'email', 'mobile', 'time') export_order = ('id', 'date_added', 'last_name', 'first_name', 'middle_name', 'email', 'mobile', 'messengers', 'status', 'source', 'course', 'consultant_name', 'consultant_surname', 'action', 'action_date', 'action_time', 'comments')
class StudentListExport(resources.ModelResource): def export(self, queryset=None, *args, **kwargs): # do the extra query annotation here, so the view need only pass in the filtered enrolments queryset card = Max( 'qa__student__other_id__number', filter=Q(qa__student__other_id__type=OtherID.Types.STUDENT_CARD)) email = Max( 'qa__student__email__email', filter=Q(qa__student__email__is_default=True), ) address = Max( 'qa__student__address__formatted', filter=Q(qa__student__address__is_default=True), ) queryset = queryset.select_related('module', 'qa', 'qa__student', 'qa__student__nationality', 'status').annotate(card=card, email=email, address=address) return super().export(queryset, *args, **kwargs) student_title = fields.Field(attribute='qa__student__title', column_name='title') first_or_nickname = fields.Field() surname = fields.Field(attribute='qa__student__surname') email_optin = fields.Field(attribute='qa__student__email_optin') nationality = fields.Field(attribute='qa__student__nationality__name') status = fields.Field(attribute='status__description') card = fields.Field(attribute='card') module_title = fields.Field(attribute='module__title') module_code = fields.Field(attribute='module__code') email = fields.Field(attribute='email') phone_numbers = fields.Field() address = fields.Field(attribute='address', widget=FormattedAddressWidget()) def dehydrate_first_or_nickname(self, enrolment: Enrolment): return enrolment.qa.student.first_or_nickname def dehydrate_phone_numbers(self, enrolment: Enrolment): return ', '.join(map(str, enrolment.qa.student.phones.all()))
class ProductResource(CustomModelResource): # id = fields.Field(default=generate_Jid(prefix='J'), # readonly=True, # widget=widgets.CharWidget(), # ) name = fields.Field( column_name='name', attribute='name', default=None, widget=widgets.CharWidget(), ) # price = fields.Field(column_name='price', attribute='price', # default=0, # widget=widgets.DecimalWidget(), # ) description = fields.Field( column_name='description', attribute='description', default=None, widget=widgets.CharWidget(), ) # producer = fields.Field(column_name='producer', attribute='producer', # default=None, # widget=widgets.CharWidget(), # ) category = fields.Field( column_name='category', attribute='category', default=None, widget=widgets.ForeignKeyWidget(ProductCategory, field='name'), ) producer = fields.Field( column_name='producer', attribute='producer', default=None, widget=widgets.ForeignKeyWidget(Producer, field='name'), ) attributes = fields.Field( column_name='attributes', attribute='attributes', default=None, widget=CustomManyToManyWidget(ProductAttribute, field="name"), ) is_active = fields.Field(column_name='is_active', attribute='is_active', default=1, widget=widgets.BooleanWidget()) discount_policy = fields.Field(column_name='discount_policy', attribute='discount_policy', default={}, widget=widgets.CharWidget()) # delete = fields.Field(column_name='delete', attribute='delete', # default=0, # widget=widgets.BooleanWidget()) # def for_delete(self, row, instance): # return self.fields['delete'].clean(row) class Meta: model = Product fields = ('id', 'name', 'description', 'producer', 'category', 'is_active', 'attributes', 'discount_policy') export_order = ('id', 'name', 'producer', 'is_active', 'category', 'attributes', 'description', 'discount_policy') # import_id_fields = ('name',) def dehydrate_str_choices(self, obj): if obj.id: return obj.str_choices()
class FounderResource(resources.ModelResource): seed = fields.Field(widget=widgets.ForeignKeyWidget(Funding), column_name='Seed') series_a = fields.Field(widget=widgets.ForeignKeyWidget(Funding), column_name='Series A') series_b = fields.Field(widget=widgets.ForeignKeyWidget(Funding), column_name='Series B') series_c = fields.Field(widget=widgets.ForeignKeyWidget(Funding), column_name='Series C') class Meta: model = Founder fields = ('user__email', 'seed', 'series_a', 'series_b', 'series_c', 'field', 'user__first_name', 'user__last_name', 'user__last_login', 'user__registered_at', 'startup_name', 'facebook', 'description', 'stage', 'employee_count', 'website') export_order = ('user__email', 'user__first_name', 'user__last_name', 'user__registered_at', 'user__last_login', 'startup_name', 'stage', 'field', 'description', 'employee_count', 'website', 'facebook', 'seed', 'series_a', 'series_b', 'series_c') def dehydrate_user_last_login(self, founder): return founder.user.last_login def dehydrate_user_registered_at(self, founder): return founder.user.registered_at def dehydrate_user_email(self, founder): return founder.user.email def dehydrate_user(self, founder): return founder.user def dehydrate_seed(self, obj): fundings = Funding.objects.filter(founder=obj.id) for f in fundings: if int(f.stage) == 0: return f.raised return 0 def dehydrate_series_a(self, obj): fundings = Funding.objects.filter(founder=obj.id) for f in fundings: if int(f.stage) == 1: return f.raised return 0 def dehydrate_series_b(self, obj): fundings = Funding.objects.filter(founder=obj.id) for f in fundings: if int(f.stage) == 2: return f.raised return 0 def dehydrate_series_c(self, obj): fundings = Funding.objects.filter(founder=obj.id) for f in fundings: if int(f.stage) == 3: return f.raised return 0 def dehydrate_stage(self, founder): return STAGE[int(founder.stage)][1] def dehydrate_field(self, founder): cat_dict = dict(CATEGORY) return cat_dict.get(founder.field, '') def get_export_headers(self): headers = [] model_fields = self.Meta.model._meta.get_fields() # + ProfileInline.model._meta.get_fields() for field in self.get_fields(): header = '' if field.column_name == 'user__last_name': header = 'Last Name' elif field.column_name == 'user__first_name': header = 'First Name' elif field.column_name == 'user__last_login': header = 'Last Login' elif field.column_name == 'user__registered_at': header = 'Registered At' elif field.column_name == 'user__email': header = 'User' else: header = next((x.verbose_name for x in model_fields if x.name == field.column_name), field.column_name) headers.append(header) return headers
class JobResource(resources.ModelResource): category = fields.Field(column_name='category', attribute='category', widget=ForeignKeyWidget(JobCategory, 'name')) class Meta: model = Job
class A(MyResource): inherited = fields.Field() class Meta: import_id_fields = ('email', )
class A(MyResource): inherited = fields.Field() class Meta: import_id_fields = ('email', ) custom_attribute = True
class ProductResource(resources.ModelResource): id = fields.Field(attribute='id', widget=IdWidget(), readonly=True) producer_name = fields.Field(attribute='producer', widget=ForeignKeyWidget( Producer, field='short_profile_name')) long_name = fields.Field(attribute='long_name') department_for_customer = fields.Field(attribute='department_for_customer', widget=TranslatedForeignKeyWidget( LUT_DepartmentForCustomer, field='short_name')) order_unit = fields.Field(attribute='order_unit', widget=ChoiceWidget( LUT_PRODUCT_ORDER_UNIT, LUT_PRODUCT_ORDER_UNIT_REVERSE)) order_average_weight = fields.Field(attribute='order_average_weight', widget=ThreeDecimalsWidget()) producer_unit_price = fields.Field(attribute='producer_unit_price', widget=TwoMoneysWidget()) customer_unit_price = fields.Field(attribute='customer_unit_price', widget=TwoMoneysWidget()) unit_deposit = fields.Field(attribute='unit_deposit', widget=TwoMoneysWidget()) vat_level = fields.Field(attribute='vat_level', widget=ChoiceWidget(LUT_ALL_VAT, LUT_ALL_VAT_REVERSE)) customer_minimum_order_quantity = fields.Field( attribute='customer_minimum_order_quantity', widget=ThreeDecimalsWidget()) customer_increment_order_quantity = fields.Field( attribute='customer_increment_order_quantity', widget=ThreeDecimalsWidget()) customer_alert_order_quantity = fields.Field( attribute='customer_alert_order_quantity', widget=ThreeDecimalsWidget()) wrapped = fields.Field(attribute='wrapped', widget=DecimalBooleanWidget()) stock = fields.Field(attribute='stock', widget=ThreeDecimalsWidget()) limit_order_quantity_to_stock = fields.Field( attribute='limit_order_quantity_to_stock', widget=DecimalBooleanWidget(), readonly=False) producer_order_by_quantity = fields.Field( attribute='producer_order_by_quantity', widget=ThreeDecimalsWidget()) label = fields.Field(attribute='production_mode', widget=TranslatedManyToManyWidget(LUT_ProductionMode, separator="; ", field='short_name')) picture = fields.Field(attribute='picture2', readonly=True) is_into_offer = fields.Field(attribute='is_into_offer', widget=DecimalBooleanWidget(), readonly=True) is_active = fields.Field(attribute='is_active', widget=DecimalBooleanWidget(), readonly=True) def before_save_instance(self, instance, using_transactions, dry_run): """ Override to add additional logic. """ if instance.wrapped is None: instance.wrapped = False if instance.producer_unit_price is None: instance.producer_unit_price = REPANIER_MONEY_ZERO if instance.customer_unit_price is None: instance.customer_unit_price = REPANIER_MONEY_ZERO if instance.unit_deposit is None: instance.unit_deposit = REPANIER_MONEY_ZERO if instance.customer_minimum_order_quantity is None: instance.customer_minimum_order_quantity = DECIMAL_ZERO if instance.customer_increment_order_quantity is None: instance.customer_increment_order_quantity = DECIMAL_ZERO if instance.customer_alert_order_quantity is None: instance.customer_alert_order_quantity = DECIMAL_ZERO if instance.stock is None: instance.stock = DECIMAL_ZERO if instance.producer_order_by_quantity is None: instance.producer_order_by_quantity = DECIMAL_ZERO if instance.order_unit is None: raise ValueError(_('The order unit must be set.')) if instance.order_unit != PRODUCT_ORDER_UNIT_DEPOSIT: if instance.producer_unit_price < DECIMAL_ZERO: raise ValueError( _('The price must be greater than or equal to zero.')) if instance.customer_unit_price < DECIMAL_ZERO: raise ValueError( _('The price must be greater than or equal to zero.')) if instance.order_unit in [ PRODUCT_ORDER_UNIT_PC, PRODUCT_ORDER_UNIT_PC_PRICE_KG, PRODUCT_ORDER_UNIT_PC_PRICE_LT, PRODUCT_ORDER_UNIT_PC_PRICE_PC, PRODUCT_ORDER_UNIT_PC_KG ]: # Do not allow decimal value when the qty represents pieces. if instance.customer_minimum_order_quantity != instance.customer_minimum_order_quantity // 1: raise ValueError( _('The minimum order quantity must be an integer.')) if instance.customer_increment_order_quantity != instance.customer_increment_order_quantity // 1: raise ValueError(_('The increment must be an integer.')) if instance.stock != instance.stock // 1: raise ValueError(_('The stock must be an integer.')) if instance.customer_alert_order_quantity != instance.customer_alert_order_quantity // 1: raise ValueError( _('The alert quantity must be an integer.')) if instance.order_unit < PRODUCT_ORDER_UNIT_DEPOSIT: if instance.customer_minimum_order_quantity <= DECIMAL_ZERO: raise ValueError( _('The minimum order quantity must be greater than zero.')) if instance.customer_minimum_order_quantity != instance.customer_alert_order_quantity \ and instance.customer_increment_order_quantity <= DECIMAL_ZERO: raise ValueError(_('The increment must be greater than zero.')) qs = Product.objects.filter(reference=instance.reference, producer=instance.producer).order_by('?') if instance.id is not None: qs = qs.exclude(id=instance.id) if qs.exists(): raise ValueError( _("The reference %(reference)s is already used by %(product)s") % { 'reference': instance.reference, 'product': qs.first() }) class Meta: model = Product fields = ('id', 'producer_name', 'reference', 'department_for_customer', 'long_name', 'order_unit', 'wrapped', 'order_average_weight', 'producer_unit_price', 'customer_unit_price', 'unit_deposit', 'vat_level', 'customer_minimum_order_quantity', 'customer_increment_order_quantity', 'customer_alert_order_quantity', 'stock', 'limit_order_quantity_to_stock', 'producer_order_by_quantity', 'label', 'picture', 'is_into_offer', 'is_active') export_order = fields import_id_fields = ('id', ) skip_unchanged = True report_skipped = False use_transactions = False
class CampusPartnerUserResource(resources.ModelResource): campus_partner = fields.Field(attribute='campus_partner', column_name="Campus Partner") user = fields.Field(attribute='user', column_name="User Name") class Meta: model = CampusPartnerUser
class ProductResource(resources.ModelResource): id = fields.Field(attribute='id', column_name='Id товару') product_category = fields.Field(column_name='Категорія товарів', attribute='product_category', widget=ForeignKeyWidget( CategoryGoods, 'category')) product_name = fields.Field(attribute='product_name', column_name='Назва товару') is_active = fields.Field( attribute='is_active', column_name='Товар активний/неактивний (True/False)') compatible_product_brand = fields.Field( attribute='compatible_product_brand', column_name='Бренди сумісності', widget=ManyToManyWidget(BrandProducts)) description = fields.Field(attribute='description', column_name='Опис товару') technical_characteristic = fields.Field( attribute='technical_characteristic', column_name='Технічна характеристика') status_product = fields.Field(column_name='Статус товару', attribute='status_product', widget=ForeignKeyWidget( StatusGoods, 'status')) product_price = fields.Field(attribute='product_price', column_name='Ціна, Грн') product_discount = fields.Field(attribute='product_discount', column_name='Знижка, %') created = fields.Field(attribute='created', column_name='Дата створення') updated = fields.Field(attribute='updated', column_name='Дата оновлення') class Meta: model = Product
class DissertationResource(resources.ModelResource): COLUMN_DISSERTATION_ID = 'TMP_DISSERTATION_ID' COLUMN_DISSERTATION_OPI_ID = 'PRACE_BADAWCZE_ID' COLUMN_DISSERTATION_TITLE = 'TYTUL' COLUMN_DISSERTATION_TITLE_SLUG = 'TMP_TITLE_SLUG' COLUMN_DISSERTATION_TITLE_TEXT = 'TMP_TITLE_TEXT' COLUMN_DISSERTATION_TYPE = 'RODZAJ_PRACY' COLUMN_DISSERTATION_SUPERVISORS = 'TMP_DISSERTATION_SUPERVISORS' COLUMN_DISSERTATION_REVIEWERS = 'TMP_DISSERTATION_REVIEWERS' COLUMN_DISSERTATION_AUTHOR = 'TMP_DISSERTATION_AUTHOR' COLUMN_DISSERTATION_DATE_START = 'DATA_ROZPOCZECIA' COLUMN_DISSERTATION_DATE_END = 'DATA_ZAKONCZENIA' COLUMN_DISSERTATION_INSTITUTION = 'NAZWA_INST' COLUMN_DISSERTATION_IS_ACCEPTED = 'TMP_DISSERTATION_IS_ACCEPTED'; # columns for people-disstertations associations COLUMN_PERSON_FUNCTION = 'FUNKCJA_OSOBY' COLUMN_PERSON_OPI_ID = 'OSOBY_ID' COLUMN_PERSON_FIRST_NAME = 'IMIE' COLUMN_PERSON_LAST_NAME = 'NAZWISKO' COLUMN_PERSON_DEGREE = 'STOPIEN' dissertation_id = fields.Field(column_name=COLUMN_DISSERTATION_ID, attribute='dissertation_id') dissertation_opi_id = fields.Field(column_name=COLUMN_DISSERTATION_OPI_ID, attribute='dissertation_opi_id') dissertation_title = fields.Field(column_name=COLUMN_DISSERTATION_TITLE, attribute='dissertation_title') dissertation_title_text = fields.Field(column_name=COLUMN_DISSERTATION_TITLE_TEXT, attribute='dissertation_title_text') dissertation_title_slug = fields.Field(column_name=COLUMN_DISSERTATION_TITLE_SLUG, attribute='dissertation_title_slug') dissertation_date_start = fields.Field(column_name=COLUMN_DISSERTATION_DATE_START, attribute='dissertation_date_start') dissertation_date_end = fields.Field(column_name=COLUMN_DISSERTATION_DATE_END, attribute='dissertation_date_end') dissertation_author = fields.Field(column_name=COLUMN_DISSERTATION_AUTHOR, attribute='dissertation_author', widget=ForeignKeyWidget(Person, field='person_id')) dissertation_supervisors = fields.Field(column_name=COLUMN_DISSERTATION_SUPERVISORS, attribute='dissertation_supervisors', widget=ManyToManyWidget(Person, separator=',', field='person_id')) dissertation_reviewers = fields.Field(column_name=COLUMN_DISSERTATION_REVIEWERS, attribute='dissertation_reviewers', widget=ManyToManyWidget(Person, separator=',', field='person_id')) dissertation_institution = fields.Field(column_name=COLUMN_DISSERTATION_INSTITUTION, attribute='dissertation_institution', widget=ForeignKeyWidget(Institution, field='institution_id')) dissertation_type = fields.Field(column_name=COLUMN_DISSERTATION_TYPE, attribute='dissertation_type') dissertation_is_accepted = fields.Field(column_name=COLUMN_DISSERTATION_IS_ACCEPTED, attribute='dissertation_is_accepted') LOG_MSG_ERR_FILE_IMPROPER = "[ERROR] Not proper input file for import Dissertation objects. Please check if following columns exist: " LOG_MSG_ADDED_OBJECT = "[SUCCESS] Dissertation object has been successfully saved. " LOG_MSG_DUPLICATE_OBJECT = "[DUPLICATE] Dissertation object potentially duplicated: " LOG_MSG_IMPORT_BEGIN = "[STARTED IMPORT] --- IMPORT DISSERTATIONS PROCESS INITIALIZED --- " LOG_MSG_IMPORT_END = "[FINISHED IMPORT] --- IMPORT DISSERTATIONS PROCESS FINISHED --- " LOG_MSG_ADDED_OBJECT = "[SUCCESS] Dissertation object has been successfully saved. " LOG_MSG_ERROR_MISSIG_DISSERTATION = "[NOT FOUND OBJECT] Dissertation object not found in database! " LOG_MSG_ERROR_MISSIG_PERSON = "[NOT FOUND OBJECT] Person object not found in database! " REPORT_FILE_IMPROPER = 'Nie poprawny format pliku dla importu prac doktorskich i habilitacyjnych. Sprawdź czy plik zawiera następujące kolumny:' REPORT_IMPORT_BEGIN = '--- -- - POCZĄTEK IMPORTU - -- ---' REPORT_IMPORT_END = '--- -- - KONIEC IMPORTU - -- ---' REPORT_DISSERTATION_NEW = 'Nowa praca' REPORT_DISSERTATION_NEW_EXIST_DUPLICATES = 'Nowa praca. Istnieją potencjalne duplikaty' REPORT_DISSERTATION_SAVED = 'Zapisano pracę' REPORT_DISSERTATION_UPDATE = 'Aktualizacja pracy. Znaleziono pracę o takim samym ID.' REPORT_DISSERTATION_DUPLICATE = 'Potencjalny duplikat pracy' REPORT_DISSERTATION_AUTHOR = 'Dodano autora pracy' REPORT_DISSERTATION_SUPERVISOR = 'Dodano promotora pracy' REPORT_DISSERTATION_REVIEWER = 'Dodano recenzenta' REPORT_SKIP_ROW = 'Pominięto wiersz' def __init__(self): self._row_to_skip = False self._skip_msg = '[SKIPPED ROW] ' self._resource_info = '' self.ENTITY_IS_ACCEPTED = False def create_resource_info(self, row): return '[SKIPPED ROW] [' + datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + '] ' + '; '.join('{}={}'.format(k, v) for k, v in row.items()) def get_skip_msg(self): return self._skip_msg def mark_row_to_skip(self, row=dict(), reason_msg=''): self._row_to_skip = True self._skip_msg = reason_msg + self.create_resource_info(row) def init_dissertation_row(self, row, is_dissertations_file): row_dissertation_opi_id = row.get(self.COLUMN_DISSERTATION_OPI_ID, '') [dissertation, dissertation_id] = self.dissertation_import_helper.try_get_dissertation_object(row_dissertation_opi_id) row[self.COLUMN_DISSERTATION_ID] = dissertation_id if dissertation is None: if (is_dissertations_file): row[self.COLUMN_DISSERTATION_AUTHOR] = None row[self.COLUMN_DISSERTATION_REVIEWERS] = None row[self.COLUMN_DISSERTATION_SUPERVISORS] = None row[self.COLUMN_DISSERTATION_IS_ACCEPTED] = self.ENTITY_IS_ACCEPTED else: #row[self.COLUMN_DISSERTATION_OPI_ID] = None row[self.COLUMN_DISSERTATION_AUTHOR] = None row[self.COLUMN_DISSERTATION_INSTITUTION] = None row[self.COLUMN_DISSERTATION_TITLE] = row[self.COLUMN_PERSON_FIRST_NAME] + ' ' + row[self.COLUMN_PERSON_LAST_NAME] row[self.COLUMN_DISSERTATION_TITLE_TEXT] = None row[self.COLUMN_DISSERTATION_TITLE_SLUG] = None row[self.COLUMN_DISSERTATION_DATE_START] = None row[self.COLUMN_DISSERTATION_DATE_END] = None row[self.COLUMN_DISSERTATION_TYPE] = None self.mark_row_to_skip(row, self.LOG_MSG_ERROR_MISSIG_DISSERTATION) # #NOTE: there is no information about dissertation in dissertations-people file else: if (is_dissertations_file): # row[self.COLUMN_DISSERTATION_AUTHOR] = dissertation.dissertation_author row[self.COLUMN_DISSERTATION_REVIEWERS] = ','.join([str(r.person_id) for r in dissertation.dissertation_reviewers.all()]) row[self.COLUMN_DISSERTATION_SUPERVISORS] = ','.join([str(s.person_id) for s in dissertation.dissertation_supervisors.all()]) row[self.COLUMN_DISSERTATION_IS_ACCEPTED] = dissertation.dissertation_is_accepted else: row[self.COLUMN_DISSERTATION_OPI_ID] = dissertation.dissertation_opi_id row[self.COLUMN_DISSERTATION_INSTITUTION] = dissertation.dissertation_institution.institution_id row[self.COLUMN_DISSERTATION_TITLE] = dissertation.dissertation_title row[self.COLUMN_DISSERTATION_TITLE_TEXT] = dissertation.dissertation_title_text row[self.COLUMN_DISSERTATION_TITLE_SLUG] = dissertation.dissertation_title_slug row[self.COLUMN_DISSERTATION_DATE_START] = dissertation.dissertation_date_start row[self.COLUMN_DISSERTATION_DATE_END] = dissertation.dissertation_date_end row[self.COLUMN_DISSERTATION_TYPE] = dissertation.dissertation_type return [row, dissertation] def get_people_and_functions(self, row, dissertation): # get person_id using opi_id row_person_opi_id = row.get(self.COLUMN_PERSON_OPI_ID, '') person_id = self.dissertation_import_helper.get_person_id(row_person_opi_id) reviewers = self.dissertation_import_helper.get_reviewers(dissertation) supervisors = self.dissertation_import_helper.get_supervisors(dissertation) if person_id is None: self.mark_row_to_skip(row, self.LOG_MSG_ERROR_MISSIG_PERSON) # #NOTE: there is no information about person in dissertations-people file row_dissertation_person_function = row.get(self.COLUMN_PERSON_FUNCTION, '') if row_dissertation_person_function is not None: if self.dissertation_import_helper.is_author(row_dissertation_person_function): row[self.COLUMN_DISSERTATION_AUTHOR] = person_id if self.dissertation_import_helper.is_reviewer(row_dissertation_person_function): if person_id not in reviewers: reviewers.append(person_id) row[self.COLUMN_DISSERTATION_REVIEWERS] = ','.join(str(r) for r in reviewers) import_report.info(';'.join((self.REPORT_DISSERTATION_REVIEWER, str(person_id), '', str(row_person_opi_id)))) if self.dissertation_import_helper.is_supervisor(row_dissertation_person_function): if person_id not in supervisors: supervisors.append(person_id) row[self.COLUMN_DISSERTATION_REVIEWERS] = ','.join(str(r) for r in reviewers) import_report.info(';'.join((self.REPORT_DISSERTATION_SUPERVISOR, str(person_id), '', str(row_person_opi_id)))) row[self.COLUMN_DISSERTATION_SUPERVISORS] = ','.join(str(s) for s in supervisors) return row def get_dissertation_data(self, row): # get dissertation_institutions row_dissertation_institutions = row.get(self.COLUMN_DISSERTATION_INSTITUTION, '') if not isinstance(row_dissertation_institutions, int): institutions = self.dissertation_import_helper.get_institutions(row_dissertation_institutions) row[self.COLUMN_DISSERTATION_INSTITUTION] = institutions[0].institution_id if institutions is not None and len(institutions) > 0 else None # get dissertation_title ant title_slug row_dissertation_opi_id = row.get(self.COLUMN_DISSERTATION_OPI_ID, '') row_dissertation_title = row.get(self.COLUMN_DISSERTATION_TITLE, '') text_title = strip_tags(row_dissertation_title) row[self.COLUMN_DISSERTATION_TITLE_TEXT] = text_title row[self.COLUMN_DISSERTATION_TITLE_SLUG] = slugify_text_title(text_title) row[self.COLUMN_DISSERTATION_TITLE] = row_dissertation_title # get date date_start = row[self.COLUMN_DISSERTATION_DATE_START] row[self.COLUMN_DISSERTATION_DATE_START] = ImportHelper.create_date_isoformat(date_start) date_end = row[self.COLUMN_DISSERTATION_DATE_END] row[self.COLUMN_DISSERTATION_DATE_END] = ImportHelper.create_date_isoformat(date_end) # get type row_dissertation_type = row[self.COLUMN_DISSERTATION_TYPE] dissertation_type = self.dissertation_import_helper.get_dissertation_type(row_dissertation_type) row[self.COLUMN_DISSERTATION_TYPE] = dissertation_type # check for duplicates [dissertation_key_exist, dissertation_duplicate_id] = self.dissertation_import_helper.check_dissertation_title(text_title) dissertation_id = row[self.COLUMN_DISSERTATION_ID] if dissertation_key_exist: if dissertation_id == dissertation_duplicate_id: logger.warning('Dissertation update. Found dissertation with the same id: dissertation_title=' + text_title + ' dissertation_id=' + str(dissertation_id)) import_report.warning(';'.join((self.REPORT_DISSERTATION_UPDATE, str(dissertation_id), text_title, row_dissertation_opi_id))) elif dissertation_id is not None: import_report.warning(';'.join((self.REPORT_DISSERTATION_NEW_EXIST_DUPLICATES, str(dissertation_id), text_title, row_dissertation_opi_id))) import_report.warning(';'.join((self.REPORT_DISSERTATION_DUPLICATE, str(dissertation_duplicate_id)))) logger.warning(self.LOG_MSG_DUPLICATE_OBJECT) logger.warning('Existing object: dissertation_title=' + text_title + ' dissertation_id=' + str(dissertation_id)) logger.warning('Duplicate object: ' + ' dissertation_id=' + str(dissertation_duplicate_id)) else: import_report.info(';'.join((self.REPORT_DISSERTATION_NEW, str(dissertation_id), text_title, row_dissertation_opi_id))) return row # # overrided functions from Resource def skip_row(self, instance, original): if self._row_to_skip: logger.warning(self.get_skip_msg()) import_report.warning(self.REPORT_SKIP_ROW + self.get_skip_msg()) return True else: return super(DissertationResource, self).skip_row(instance, original) def before_import(self, dataset, using_transactions, dry_run, **kwargs): self.ENTITY_IS_ACCEPTED = getattr(settings, "IMPORT_AUTO_PUBLICATION", False) # check columns set columns_set = {self.COLUMN_DISSERTATION_OPI_ID, self.COLUMN_DISSERTATION_TITLE, self.COLUMN_DISSERTATION_TYPE, self.COLUMN_DISSERTATION_DATE_START, self.COLUMN_DISSERTATION_DATE_END, self.COLUMN_DISSERTATION_INSTITUTION, self.COLUMN_DISSERTATION_AUTHOR, self.COLUMN_PERSON_DEGREE, self.COLUMN_PERSON_OPI_ID, self.COLUMN_PERSON_FIRST_NAME, self.COLUMN_PERSON_LAST_NAME, self.COLUMN_PERSON_FUNCTION} if not set(dataset.headers) <= columns_set: logger.error(self.LOG_MSG_ERR_FILE_IMPROPER + ', '.join(columns_set)) logger.info(self.LOG_MSG_IMPORT_BEGIN + timezone.now().strftime('%B %d, %Y, %I:%M %p')) import_report.info(self.REPORT_IMPORT_BEGIN + timezone.now().strftime('%B %d, %Y, %I:%M %p') + ';BIULETYN_ID ;TYTUŁ PRACY ;OPI_ID ;NAZWA INSTYTUCJI ') self.dissertation_import_helper = DissertationImportHelper.instance() return super(DissertationResource, self).before_import(dataset, using_transactions, dry_run, **kwargs) def after_import(self, dataset, result, using_transactions, dry_run, **kwargs): logger.info(self.LOG_MSG_IMPORT_END + timezone.now().strftime('%B %d, %Y, %I:%M %p')) import_report.info(self.REPORT_IMPORT_END + timezone.now().strftime('%B %d, %Y, %I:%M %p')) # clear memory if not dry_run: DissertationImportHelper.destroy_instance() return super(DissertationResource, self).after_import(dataset, result, using_transactions, dry_run, **kwargs) def before_import_row(self, row, **kwargs): self._row_to_skip = False # by default row shouldn't be skipped is_dissertations_file = self.COLUMN_DISSERTATION_TYPE in row is_dissertations_people_file = self.COLUMN_PERSON_FUNCTION in row # get dissertation_id using opi_id [row, dissertation] = self.init_dissertation_row(row, is_dissertations_file) if is_dissertations_people_file: self.get_people_and_functions(row, dissertation) else: self.get_dissertation_data(row) return super(DissertationResource, self).before_import_row(row, **kwargs) def before_save_instance(self, instance, using_transactions, dry_run): instance.is_imported = True return super(DissertationResource, self).before_save_instance(instance, using_transactions, dry_run) def after_save_instance(self, instance, using_transactions, dry_run): if dry_run: return #update dissertations dictionary (to avoid query database) self.dissertation_import_helper.dissertations_ids_dict[instance.dissertation_id] = instance if instance.dissertation_institution is not None and instance.dissertation_institution not in instance.dissertation_authorizations.all(): #add institution as authorized DissertationAuthorized.objects.create(dissertation=instance, authorized=instance.dissertation_institution) logger.info(self.LOG_MSG_ADDED_OBJECT + ("%d %s" % (instance.dissertation_id, instance.dissertation_title))) import_report.info(';'.join((self.REPORT_DISSERTATION_SAVED, str(instance.dissertation_id), instance.dissertation_title, str(instance.dissertation_opi_id)))) return super(DissertationResource, self).after_save_instance(instance, using_transactions, dry_run) def import_data(self, dataset, dry_run=False, raise_errors=False, use_transactions=None, collect_failed_rows=False, **kwargs): if dry_run: logging.disable(logging.CRITICAL) else: logging.disable(logging.NOTSET) return super(DissertationResource, self).import_data(dataset, dry_run, raise_errors, use_transactions, collect_failed_rows, **kwargs) class Meta: fields = ('dissertation_type', 'dissertation_opi_id', 'dissertation_title_text', 'dissertation_date_start', 'dissertation_date_end', 'dissertation_institution', 'dissertation_reviewers',) import_id_fields = ('dissertation_id',) skip_unchanged = False report_skipped = True model = Dissertation
class ReporteActividadResource(resources.ModelResource): valor_wp_eur = fields.Field( column_name='valor wp eur', attribute='valor_wp_eur', ) fecha_integracion = fields.Field(column_name='fecha integracion', attribute='fecha_integracion', widget=DateWidget(format='%d/%m/%Y')) grupo_gap = fields.Field( column_name='grupo gap', attribute='grupo_gap', ) tipo_trabajo_noc = fields.Field( column_name='tipo trabajo noc', attribute='tipo_trabajo_noc', ) estado_noc = fields.Field( column_name='estado noc', attribute='estado_noc', ) subestado_noc = fields.Field( column_name='subestado noc', attribute='subestado_noc', ) responsable_ni = fields.Field( column_name='responsable ni', attribute='responsable_ni', ) estado_ni = fields.Field( column_name='estado ni', attribute='estado_ni', ) concepto_ni = fields.Field( column_name='concepto ni', attribute='concepto_ni', ) tipo_intervencion_ni = fields.Field( column_name='tipo intervencion ni', attribute='tipo_intervencion_ni', ) fecha_asignacion_ni = fields.Field(column_name='fecha asignacion ni', attribute='fecha_asignacion_ni', widget=DateWidget(format='%d/%m/%Y')) requiere_hw = fields.Field( column_name='requiere hw', attribute='requiere_hw', ) responsable_actual = fields.Field( column_name='responsable actual', attribute='reresponsable_actual', ) responsable_npo = fields.Field( column_name='responsable npo', attribute='responsable_npo', ) estado_npo = fields.Field( column_name='estado npo', attribute='estado_npo', ) posible_causa = fields.Field( column_name='posible causa', attribute='posible_causa', ) concepto_npo = fields.Field( column_name='concepto npo', attribute='concepto_npo', ) tipo_intervencion_npo = fields.Field( column_name='tipo intervencion npo', attribute='tipo_intervencion_npo', ) fecha_asignacion_npo = fields.Field(column_name='fecha asignacion npo', attribute='fecha_asignacion_npo', widget=DateWidget(format='%d/%m/%Y')) fecha_fc_visita = fields.Field(column_name='fecha fc visita', attribute='fecha_fc_visita', widget=DateWidget(format='%d/%m/%Y')) id_siteaccess = fields.Field( column_name='id siteaccess', attribute='id_siteaccess', ) class Meta: model = ReporteActividad exclude = ('id', 'gap_administrador', 'creado', 'actualizado') export_order = ( 'wp', 'agrupador', 'estacion', 'regional', 'ciudad', 'banda', 'valor_wp_eur', 'proyecto', 'escenario', 'fecha_integracion', 'grupo_gap', 'tipo_trabajo_noc', 'estado_noc', 'subestado_noc', 'responsable_ni', 'estado_ni', 'concepto_ni', 'tipo_intervencion_ni', 'fecha_asignacion_ni', 'requiere_hw', 'responsable_actual', 'responsable_npo', 'estado_npo', 'posible_causa', 'concepto_npo', 'tipo_intervencion_npo', 'fecha_asignacion_npo', 'supervisor', 'fecha_fc_visita', 'id_siteaccess', )
class EnrollmentResource(resources.ModelResource): governorate = fields.Field( column_name='governorate', attribute='school', widget=ForeignKeyWidget(School, 'location_parent_name') ) district = fields.Field( column_name='district', attribute='school', widget=ForeignKeyWidget(School, 'location_name') ) student_age = fields.Field(column_name='Student age') cycle_name = fields.Field(column_name='Cycle') class Meta: model = Enrollment form = EnrollmentAdminForm fields = ( 'id', 'new_registry', 'student_outreached', 'have_barcode', 'outreach_barcode', 'registration_date', 'student__id', 'student__id_type', 'student__id_number', 'student__number', 'student__first_name', 'student__father_name', 'student__last_name', 'student__mother_fullname', 'student__birthday_year', 'student__birthday_month', 'student__birthday_day', 'student__place_of_birth', 'student_age', 'student__sex', 'student__nationality__name', 'student__phone_prefix', 'student__phone', 'student__address', 'governorate', 'district', 'school__number', 'school__name', 'section__name', 'classroom__name', 'cycle_name', 'number_in_previous_school', 'last_education_level__name', 'last_education_year', 'last_school_type', 'last_school_shift', 'last_school__name', 'last_school__number', 'last_year_result', 'participated_in_alp', 'last_informal_edu_round__name', 'last_informal_edu_final_result__name', 'age_min_restricted', 'age_max_restricted', 'last_attendance_date', 'last_absent_date', 'created', 'modified', 'moved', 'dropout_status', 'disabled', ) export_order = fields def dehydrate_student_age(self, obj): return obj.student_age def dehydrate_cycle_name(self, obj): return obj.cycle
class MyResource(resources.Resource): name = fields.Field() email = fields.Field() class Meta: column_order = ('email', 'name')
class B(BookResource): delete = fields.Field(widget=widgets.BooleanWidget()) def for_delete(self, row, instance): return self.fields['delete'].clean(row)
class CommunityPartnerUserResource(resources.ModelResource): community_partner = fields.Field(attribute='community_partner', column_name="Community Partner") user = fields.Field(attribute='user', column_name="User Name") class Meta: model = CommunityPartnerUser
class B(BookResource): total_categories = fields.Field('total_categories', readonly=True) class Meta: model = Book skip_unchanged = True
class CommunityPartnerResource(resources.ModelResource): community_type = fields.Field(attribute='community_type', column_name="Community Type") class Meta: model = CommunityPartner fields = ('name', 'website_url', 'community_type', 'k12_level','address_line1', 'address_line2', 'country', 'county', 'city', 'state', 'zip', 'latitude','longitude','active', 'weitz_cec_part')
class B(A): local = fields.Field() class Meta: export_order = ('email', 'extra')
class RSResource(resources.ModelResource): arabic_reading_improvement = fields.Field( column_name='arabic_reading_improvement', attribute='arabic_reading_improvement', ) pretest_result = fields.Field( column_name='pretest_result', attribute='pretest_result', ) posttest_result = fields.Field( column_name='posttest_result', attribute='posttest_result', ) arabic_improvement = fields.Field( column_name='arabic_improvement', attribute='arabic_improvement', ) language_improvement = fields.Field( column_name='language_improvement', attribute='language_improvement', ) science_improvement = fields.Field( column_name='science_improvement', attribute='science_improvement', ) math_improvement = fields.Field( column_name='math_improvement', attribute='math_improvement', ) academic_test_improvement = fields.Field( column_name='academic_test_improvement', attribute='academic_test_improvement', ) pre_test_score = fields.Field( column_name='pre_test_score', attribute='pre_test_score', ) post_test_score = fields.Field( column_name='post_test_score', attribute='post_test_score', ) assessment_improvement = fields.Field( column_name='assessment_improvement', attribute='assessment_improvement', ) pre_motivation_score = fields.Field( column_name='pre_motivation_score', attribute='pre_motivation_score', ) post_motivation_score = fields.Field( column_name='post_motivation_score', attribute='post_motivation_score', ) motivation_improvement = fields.Field( column_name='motivation_improvement', attribute='motivation_improvement', ) pre_self_assessment_score = fields.Field( column_name='pre_self_assessment_score', attribute='pre_self_assessment_score', ) post_self_assessment_score = fields.Field( column_name='post_self_assessment_score', attribute='post_self_assessment_score', ) self_assessment_improvement = fields.Field( column_name='self_assessment_improvement', attribute='self_assessment_improvement', ) class Meta: model = RS fields = ( 'id', 'partner__name', 'new_registry', 'round__name', 'type', 'site', 'school', 'governorate__name', 'district__name', 'location', 'language', 'student__id', 'student__id_type', 'student__id_number', 'student__number', 'student__first_name', 'student__father_name', 'student__last_name', 'student__mother_fullname', 'student__birthday_year', 'student__birthday_month', 'student__birthday_day', 'student__nationality__name', 'student__sex', 'student__p_code', 'disability__name', 'internal_number', 'comments', 'hh_educational_level', 'student__family_status', 'student__have_children', 'have_labour', 'labours', 'labour_hours', 'registered_in_school', 'shift', 'grade', 'section', 'referral', 'pre_reading_score', 'post_reading_score', 'arabic_reading_improvement', 'pretest_result', 'posttest_result', 'arabic_improvement', 'language_improvement', 'science_improvement', 'math_improvement', 'academic_test_improvement', 'pre_test_score', 'post_test_score', 'assessment_improvement', 'pre_motivation_score', 'post_motivation_score', 'motivation_improvement', 'pre_self_assessment_score', 'post_self_assessment_score', 'self_assessment_improvement', 'participation', 'barriers', 'learning_result', 'created', 'modified' ) export_order = fields
class B(A): local = fields.Field()
class BLNResource(resources.ModelResource): arabic_improvement = fields.Field( column_name='arabic improvement', attribute='arabic_improvement', ) english_improvement = fields.Field( column_name='english_improvement', attribute='english_improvement', ) french_improvement = fields.Field( column_name='french_improvement', attribute='french_improvement', ) math_improvement = fields.Field( column_name='math_improvement', attribute='math_improvement', ) assessment_improvement = fields.Field( column_name='assessment_improvement', attribute='assessment_improvement', ) pre_test_arabic = fields.Field(column_name='pre test arabic') pre_test_foreign_language = fields.Field(column_name='pre_test_foreign_language') pre_test_math = fields.Field(column_name='pre_test_math') post_test_arabic = fields.Field(column_name='post_test_arabic') post_test_foreign_language = fields.Field(column_name='post_test_foreign_language') post_test_math = fields.Field(column_name='post_test_math') class Meta: fields = ( 'id', 'partner__name', 'new_registry', 'student_outreached', 'have_barcode', 'outreach_barcode', 'round__name', 'governorate__name', 'district__name', 'location', 'language', 'student__id', 'student__id_type', 'student__id_number', 'student__number', 'student__first_name', 'student__father_name', 'student__last_name', 'student__mother_fullname', 'student__birthday_year', 'student__birthday_month', 'student__birthday_day', 'student__nationality__name', 'student__sex', 'student__p_code', 'disability__name', 'internal_number', 'comments', 'hh_educational_level', 'student__family_status', 'student__have_children', 'have_labour', 'labours', 'labour_hours', 'pre_test_arabic', 'pre_test_foreign_language', 'pre_test_math', 'pre_test_score', 'post_test_arabic', 'post_test_foreign_language', 'post_test_math', 'post_test_score', 'arabic_improvement', 'english_improvement', 'french_improvement', 'math_improvement', 'assessment_improvement', 'participation', 'barriers', 'learning_result', 'created', 'modified' ) model = BLN export_order = fields def dehydrate_pre_test_arabic(self, obj): return obj.get_assessment_value('arabic', 'pre_test') def dehydrate_pre_test_foreign_language(self, obj): return obj.get_assessment_value('foreign_language', 'pre_test') def dehydrate_pre_test_math(self, obj): return obj.get_assessment_value('math', 'pre_test') def dehydrate_post_test_arabic(self, obj): return obj.get_assessment_value('arabic', 'post_test') def dehydrate_post_test_foreign_language(self, obj): return obj.get_assessment_value('foreign_language', 'post_test') def dehydrate_post_test_math(self, obj): return obj.get_assessment_value('math', 'post_test')
class TicketSchoolResource(resources.ModelResource): queue_name = fields.Field(column_name='Category') owner_name = fields.Field(column_name='User') school_cerd = fields.Field(column_name='School CERD') school_name = fields.Field(column_name='School') is_2nd_shift = fields.Field(column_name='is 2nd-shift') is_alp = fields.Field(column_name='is ALP') comments = fields.Field(column_name='Comments') status_name = fields.Field(column_name='Status') priority_name = fields.Field(column_name='Priority') class Meta: model = Ticket fields = ( 'id', 'school_cerd', 'school_name', 'owner_name', 'submitter_email', 'is_2nd_shift', 'is_alp', 'queue_name', 'title', 'description', 'comments', 'priority_name', 'created', 'status_name', ) export_order = fields def dehydrate_queue_name(self, obj): return obj.queue.title def dehydrate_owner(self, obj): if obj.submitter_email: return User.objects.filter(email=obj.submitter_email).first() return '' def dehydrate_owner_name(self, obj): if obj.submitter_email: return self.dehydrate_owner(obj).username return '' def dehydrate_school(self, obj): if self.dehydrate_owner(obj): return self.dehydrate_owner(obj).school return '' def dehydrate_school_name(self, obj): if self.dehydrate_school(obj): return self.dehydrate_school(obj).name return '' def dehydrate_school_cerd(self, obj): if self.dehydrate_school(obj): return self.dehydrate_school(obj).number return '' def dehydrate_is_2nd_shift(self, obj): if self.dehydrate_school(obj): return self.dehydrate_school(obj).is_2nd_shift return False def dehydrate_is_alp(self, obj): if self.dehydrate_school(obj): return self.dehydrate_school(obj).is_alp return False def dehydrate_comments(self, obj): if obj.followup_set: return '\r\n'.join([f.comment for f in obj.followup_set.all()]) return '' def dehydrate_status_name(self, obj): if obj.status: return force_text(dict(Ticket.STATUS_CHOICES)[obj.status]) return '' def dehydrate_priority_name(self, obj): if obj.priority: return force_text(dict(Ticket.PRIORITY_CHOICES)[obj.priority]) return ''
class CBECEResource(resources.ModelResource): pre_test_score = fields.Field( column_name='pre_test_score', attribute='pre_test_score', ) post_test_score = fields.Field( column_name='post_test_score', attribute='post_test_score', ) art_improvement = fields.Field( column_name='art_improvement', attribute='art_improvement', ) cognitive_improvement = fields.Field( column_name='cognitive_improvement', attribute='cognitive_improvement', ) social_improvement = fields.Field( column_name='social_improvement', attribute='social_improvement', ) psycho_improvement = fields.Field( column_name='psycho_improvement', attribute='psycho_improvement', ) artistic_improvement = fields.Field( column_name='artistic_improvement', attribute='artistic_improvement', ) assessment_improvement = fields.Field( column_name='assessment_improvement', attribute='assessment_improvement', ) pre_test_LanguageArtDomain = fields.Field(column_name='pre_test_LanguageArtDomain') pre_test_CognitiveDomian = fields.Field(column_name='pre_test_CognitiveDomian') pre_test_ScienceDomain = fields.Field(column_name='pre_test_ScienceDomain') pre_test_SocialEmotionalDomain = fields.Field(column_name='pre_test_SocialEmotionalDomain') pre_test_PsychomotorDomain = fields.Field(column_name='pre_test_PsychomotorDomain') pre_test_ArtisticDomain = fields.Field(column_name='pre_test_ArtisticDomain') post_test_LanguageArtDomain = fields.Field(column_name='post_test_LanguageArtDomain') post_test_CognitiveDomian = fields.Field(column_name='post_test_CognitiveDomian') post_test_ScienceDomain = fields.Field(column_name='post_test_ScienceDomain') post_test_SocialEmotionalDomain = fields.Field(column_name='post_test_SocialEmotionalDomain') post_test_PsychomotorDomain = fields.Field(column_name='post_test_PsychomotorDomain') post_test_ArtisticDomain = fields.Field(column_name='post_test_ArtisticDomain') class Meta: model = CBECE fields = ( 'id', 'partner__name', 'new_registry', 'student_outreached', 'have_barcode', 'outreach_barcode', 'round__name', 'cycle', 'site', 'school', 'governorate__name', 'district__name', 'location', 'language', 'referral', 'student__id', 'student__id_type', 'student__id_number', 'student__number', 'student__first_name', 'student__father_name', 'student__last_name', 'student__mother_fullname', 'student__birthday_year', 'student__birthday_month', 'student__birthday_day', 'student__nationality__name', 'student__sex', 'student__p_code', 'disability__name', 'internal_number', 'comments', 'child_muac', 'hh_educational_level', 'have_labour', 'labours', 'labour_hours', 'pre_test_LanguageArtDomain', 'pre_test_CognitiveDomian', 'pre_test_ScienceDomain', 'pre_test_SocialEmotionalDomain', 'pre_test_PsychomotorDomain', 'pre_test_ArtisticDomain', 'pre_test_score', 'post_test_LanguageArtDomain', 'post_test_CognitiveDomian', 'post_test_ScienceDomain', 'post_test_SocialEmotionalDomain', 'post_test_PsychomotorDomain', 'post_test_ArtisticDomain', 'post_test_score', 'art_improvement', 'cognitive_improvement', 'social_improvement', 'psycho_improvement', 'artistic_improvement', 'assessment_improvement', 'participation', 'barriers', 'learning_result', 'created', 'modified' ) export_order = fields def dehydrate_pre_test_LanguageArtDomain(self, obj): return obj.get_assessment_value('LanguageArtDomain', 'pre_test') def dehydrate_pre_test_CognitiveDomian(self, obj): return obj.get_assessment_value('CognitiveDomian', 'pre_test') def dehydrate_pre_test_ScienceDomain(self, obj): return obj.get_assessment_value('ScienceDomain', 'pre_test') def dehydrate_pre_test_SocialEmotionalDomain(self, obj): return obj.get_assessment_value('SocialEmotionalDomain', 'pre_test') def dehydrate_pre_test_PsychomotorDomain(self, obj): return obj.get_assessment_value('PsychomotorDomain', 'pre_test') def dehydrate_pre_test_ArtisticDomain(self, obj): return obj.get_assessment_value('ArtisticDomain', 'pre_test') def dehydrate_post_test_LanguageArtDomain(self, obj): return obj.get_assessment_value('LanguageArtDomain', 'post_test') def dehydrate_post_test_CognitiveDomian(self, obj): return obj.get_assessment_value('CognitiveDomian', 'post_test') def dehydrate_post_test_ScienceDomain(self, obj): return obj.get_assessment_value('ScienceDomain', 'post_test') def dehydrate_post_test_SocialEmotionalDomain(self, obj): return obj.get_assessment_value('SocialEmotionalDomain', 'post_test') def dehydrate_post_test_PsychomotorDomain(self, obj): return obj.get_assessment_value('PsychomotorDomain', 'post_test') def dehydrate_post_test_ArtisticDomain(self, obj): return obj.get_assessment_value('ArtisticDomain', 'post_test')
class QuestionOptionResource(resources.ModelResource): full_title = fields.Field() class Meta: model = Question_option def dehydrate_full_title(self, Question_option): return '%s' % (Question_option.question.title)
class BookResource(resources.ModelResource): published = fields.Field(column_name='published_date') class Meta: model = Book exclude = ('imported', )
class PackageTransactionResource(resources.ModelResource): class Meta: model = models.PackageTransaction fields = ( 'id', 'payment_complete_date', 'user_attendance', 'user_attendance__name', 'user_attendance__userprofile__telephone', 'user_attendance__userprofile__user__email', 'created', 'realized', 'status', 'user_attendance__team__subsidiary__address_street', 'user_attendance__team__subsidiary__address_psc', 'user_attendance__team__subsidiary__address_city', 'user_attendance__team__subsidiary__company__name', 'company_admin_email', 't_shirt_size__name', 'author__username', 'team_package__box__delivery_batch__id', 'team_package__box__id', 'team_package__box__carrier_identification', 'team_package__id', ) export_order = fields payment_complete_date = fields.Field() def dehydrate_payment_complete_date(self, obj): if obj.user_attendance.representative_payment: return obj.user_attendance.payment_complete_date() user_attendance__name = fields.Field() def dehydrate_user_attendance__name(self, obj): return "%s %s" % (obj.user_attendance.first_name(), obj.user_attendance.last_name()) user_attendance__team__subsidiary__address_street = fields.Field() def dehydrate_user_attendance__team__subsidiary__address_street(self, obj): if obj.user_attendance.team: return "%s %s" % ( obj.user_attendance.team.subsidiary.address_street, obj.user_attendance.team.subsidiary.address_street_number) user_attendance__team__subsidiary__address_psc = fields.Field() def dehydrate_user_attendance__team__subsidiary__address_psc(self, obj): if obj.user_attendance.team: return obj.user_attendance.team.subsidiary.address_psc user_attendance__team__subsidiary__address_city = fields.Field() def dehydrate_user_attendance__team__subsidiary__address_city(self, obj): if obj.user_attendance.team: return obj.user_attendance.team.subsidiary.address_city company_admin_email = fields.Field() def dehydrate_company_admin_email(self, obj): company_admin = obj.user_attendance.get_asociated_company_admin() if company_admin: return company_admin.first().userprofile.user.email else: return ""
class BookResource(resources.ModelResource): name = fields.Field(attribute='name', widget=widgets.CharWidget()) class Meta: model = Book import_id_fields = ['name']
class TalkProposalResource(resources.ModelResource): name = fields.Field(attribute='submitter__speaker_name') email = fields.Field(attribute='submitter__email') stage_1_plus_1_count = fields.Field() stage_1_plus_0_count = fields.Field() stage_1_minus_0_count = fields.Field() stage_1_minus_1_count = fields.Field() stage_2_plus_1_count = fields.Field() stage_2_plus_0_count = fields.Field() stage_2_minus_0_count = fields.Field() stage_2_minus_1_count = fields.Field() def dehydrate_stage_1_plus_1_count(self, obj): return self.data[obj.id]['stage_1']['+1'] def dehydrate_stage_1_plus_0_count(self, obj): return self.data[obj.id]['stage_1']['+0'] def dehydrate_stage_1_minus_0_count(self, obj): return self.data[obj.id]['stage_1']['-0'] def dehydrate_stage_1_minus_1_count(self, obj): return self.data[obj.id]['stage_1']['-1'] def dehydrate_stage_2_plus_1_count(self, obj): return self.data[obj.id]['stage_2']['+1'] def dehydrate_stage_2_plus_0_count(self, obj): return self.data[obj.id]['stage_2']['+0'] def dehydrate_stage_2_minus_0_count(self, obj): return self.data[obj.id]['stage_2']['-0'] def dehydrate_stage_2_minus_1_count(self, obj): return self.data[obj.id]['stage_2']['-1'] def prepare(self, obj): self.count = 0 self.data[obj.id] = { 'stage_1': {"+1": 0, "+0": 0, "-0": 0, "-1": 0}, 'stage_2': {"+1": 0, "+0": 0, "-0": 0, "-1": 0}, } reviewer = [] for review in obj.review_set.all().order_by('-updated'): if review.reviewer.email not in reviewer: reviewer.append(review.reviewer.email) self.data[obj.id]['stage_%d' % review.stage][review.vote] += 1 self.count += 1 def before_export(self, queryset, *args, **kwargs): self.data = {} super().before_export(queryset, *args, **kwargs) queryset = self.get_queryset() list(map(lambda obj: self.prepare(obj), queryset)) class Meta: model = TalkProposal fields = [ 'id', 'title', 'category', 'python_level', 'duration', 'language', 'name', 'email', 'cancelled', 'accepted', 'last_updated_at', 'stage_1_plus_1_count', 'stage_1_plus_0_count', 'stage_1_minus_0_count', 'stage_1_minus_1_count', 'stage_2_plus_1_count', 'stage_2_plus_0_count', 'stage_2_minus_0_count', 'stage_2_minus_1_count', 'remoting_policy', 'referring_policy' ] export_order = fields
class BankAccountResource(resources.ModelResource): id = fields.Field(attribute="id", widget=IdWidget(), readonly=True) permanence = fields.Field(attribute="permanence", readonly=True) operation_date = fields.Field(attribute="operation_date", widget=DateWidgetExcel()) operation_status = fields.Field(attribute="operation_status", readonly=True) producer_name = fields.Field( attribute="producer", widget=ProducerNameWidget(Producer, field="short_profile_name"), ) customer_name = fields.Field( attribute="customer", widget=CustomerNameWidget(Customer, field="short_basket_name"), ) bank_amount_in = fields.Field(attribute="bank_amount_in", widget=TwoMoneysWidget()) bank_amount_out = fields.Field(attribute="bank_amount_out", widget=TwoMoneysWidget()) customer_invoice = fields.Field( attribute="customer_invoice__date_balance", widget=DateWidgetExcel(), readonly=True, ) producer_invoice = fields.Field( attribute="producer_invoice__date_balance", widget=DateWidgetExcel(), readonly=True, ) def before_save_instance(self, instance, using_transactions, dry_run): """ Override to add additional logic. """ if instance.id is None: if instance.producer is None and instance.customer is None: if (instance.bank_amount_out is not None and instance.bank_amount_out != DECIMAL_ZERO): only_one_target = (ProducerInvoice.objects.filter( status=PERMANENCE_SEND, total_price_with_tax=instance.bank_amount_out, ).order_by("?").count()) if only_one_target == 1: instance.producer = (ProducerInvoice.objects.filter( status=PERMANENCE_SEND, total_price_with_tax=instance.bank_amount_out, ).order_by("?").first().producer) elif (instance.bank_amount_in is not None and instance.bank_amount_in != DECIMAL_ZERO): only_one_target = (CustomerInvoice.objects.filter( status=PERMANENCE_SEND, total_price_with_tax=instance.bank_amount_in, ).order_by("?").count()) if only_one_target == 1: instance.customer = (CustomerInvoice.objects.filter( status=PERMANENCE_SEND, total_price_with_tax=instance.bank_amount_in, ).order_by("?").first().customer) if instance.producer is None and instance.customer is None: raise ValueError(_("No producer nor customer found.")) if instance.bank_amount_out is None: instance.bank_amount_out = DECIMAL_ZERO if instance.bank_amount_in is None: instance.bank_amount_in = DECIMAL_ZERO if instance.producer is not None and instance.customer is not None: raise ValueError( _("Only a customer or a producer may be entered.")) if instance.producer is not None: if BankAccount.objects.filter( producer=instance.producer, bank_amount_in=instance.bank_amount_in, bank_amount_out=instance.bank_amount_out, operation_date=instance.operation_date, ).exists(): raise ValueError(_("This movement already exists.")) if BankAccount.objects.filter( producer=instance.producer, bank_amount_in=instance.bank_amount_in, bank_amount_out=instance.bank_amount_out, operation_comment=instance.operation_comment, ).exists(): raise ValueError(_("This movement already exists.")) if instance.customer is not None: if BankAccount.objects.filter( customer=instance.customer, bank_amount_in=instance.bank_amount_in, bank_amount_out=instance.bank_amount_out, operation_date=instance.operation_date, ).exists(): raise ValueError(_("This movement already exists.")) if BankAccount.objects.filter( customer=instance.customer, bank_amount_in=instance.bank_amount_in, bank_amount_out=instance.bank_amount_out, operation_comment=instance.operation_comment, ).exists(): raise ValueError(_("This movement already exists.")) def skip_row(self, instance, original): if instance.id is not None: # The import may not be used to update bank movements. return True super(BankAccountResource, self).skip_row(instance, original) class Meta: model = BankAccount fields = ( "id", "permanence", "operation_date", "operation_status", "producer_name", "customer_name", "bank_amount_in", "bank_amount_out", "operation_comment", "customer_invoice", "producer_invoice", ) export_order = fields import_id_fields = ("id", ) skip_unchanged = True report_skipped = False use_transactions = False