Beispiel #1
0
class SampleResource(resources.ModelResource):
    parent_id = fields.Field(column_name='parent_id',
                             attribute='parent_id',
                             widget=widgets.ForeignKeyWidget(Sample, 'name'))
    sub_sample_id = fields.Field(column_name='sub_sample_id',
                                 attribute='sub_sample_id',
                                 widget=widgets.ManyToManyWidget(Sample,
                                                                 field='name'))
    project = fields.Field(column_name='project',
                           attribute='project',
                           widget=widgets.ManyToManyWidget(Project,
                                                           field='name'))

    class Meta:
        model = Sample
        exclude = ('id', 'created_at', 'updated_at')
        import_id_fields = ['name']
        skip_unchanged = True
        report_skipped = False
        fields = ('name', 'alias', 'sample_type', 'description', 'project',
                  'author', 'sequence', 'length', 'genbank',
                  'source_reference', 'comments', 'parent_id', 'organism',
                  'genus_specie', 'marker', 'application', 'strategy',
                  'seq_verified', 'origin_rep', 'cloning_system', 'strand',
                  'order_number', 'part_type', 'moclo_type', 'sub_sample_id',
                  'primer_id', 'end', 'direction', 'tm')
class ProgressResource(resources.ModelResource):
    language = fields.Field("language", "language", widgets.ForeignKeyWidget(Language, "code"), None)
    type = fields.Field("type", "type", widgets.ForeignKeyWidget(Document, "code"), None)
    methods = fields.Field("methods", "methods", widgets.ManyToManyWidget(Method, ",", "name"), None)
    partners = fields.Field("partners", "partners", widgets.ManyToManyWidget(Partner, ",", "name"), None)

    class Meta:
        model = Progress
        fields = ("id", "language", "type", "is_online", "methods", "completion_rate", "completion_date", "qa_level",
                  "in_door43", "in_uw", "partners", "notes", "is_done")
Beispiel #3
0
class PlateResource(resources.ModelResource):
    name = fields.Field(
        column_name='well',
        attribute='name',
    )
    plate = fields.Field(column_name='plate',
                         attribute='plate',
                         widget=widgets.ForeignKeyWidget(Plate, field='name'))
    samples = fields.Field(column_name='samples',
                           attribute='samples',
                           widget=widgets.ManyToManyWidget(Sample,
                                                           field='name'))
    alias = fields.Field(column_name='alias',
                         attribute='samples',
                         widget=widgets.ManyToManyWidget(Sample,
                                                         field='alias'))

    # project = fields.Field(
    #     column_name='project',
    #     attribute='plate',
    #     widget=widgets.ManyToManyWidget(Plate, field='project')
    # )

    # def import_row(self, row, instance_loader, **kwargs):
    #     # overriding import_row to ignore errors and skip rows that fail to import
    #     # without failing the entire import
    #     import_result = super(PlateResource, self).import_row(row, instance_loader, **kwargs)
    #     if import_result.import_type == RowResult.IMPORT_TYPE_ERROR:
    #         # Copy the values to display in the preview report
    #         import_result.diff = [row[val] for val in row]
    #         # Add a column with the error message
    #         import_result.diff.append('Errors: {}'.format([err.error for err in import_result.errors]))
    #         # clear errors and mark the record to skip
    #         import_result.errors = []
    #         import_result.import_type = RowResult.IMPORT_TYPE_SKIP
    #
    #     return import_result

    class Meta:
        exclude = ('id', )
        import_id_fields = ['name', 'plate']
        # skip_unchanged = True
        # report_skipped = True
        # raise_errors = False
        model = Well
        #TODO: Add project column in plate import export files
        fields = ('name', 'plate', 'samples', 'alias', 'volume',
                  'concentration', 'active', 'status')

        # export_order = ('plate', 'name', 'samples', 'volume', 'concentration', 'active', 'status')

        def get_queryset(self):
            return self.model.objects.all().order_by('name')
Beispiel #4
0
class EventAttendanceResource(resources.ModelResource):
    email = AppendingField(column_name='email',
                           attribute='attendees',
                           widget=widgets.ManyToManyWidget(
                               Person, ',', 'email'))
    event_uid = fields.Field(column_name='event_uid',
                             attribute='uid',
                             widget=widgets.CharWidget(),
                             saves_null_values=False)
    event_instance_id = fields.Field(column_name='event_instance_id',
                                     attribute='instance_id',
                                     widget=widgets.CharWidget(),
                                     saves_null_values=False)

    def skip_row(self, instance, previous):
        if instance.uid is None:
            return True
        return super(EventAttendanceResource,
                     self).skip_row(instance, previous)

    class Meta:
        model = Event
        instance_loader_class = PartialMatchModelInstanceLoader
        import_id_fields = ('event_uid', 'event_instance_id')
        fields = ('uid', 'instance_id', 'attendees')
class ManifestResource(BaseContentResource):
    """
    Resource for import/export of manifest entities
    """

    blobs = fields.Field(
        column_name="blobs",
        attribute="blobs",
        widget=widgets.ManyToManyWidget(Blob, field="digest"),
    )
    config_blob = fields.Field(
        column_name="config_blob",
        attribute="config_blob",
        widget=widgets.ForeignKeyWidget(Blob, field="digest"),
    )

    def set_up_queryset(self):
        """
        :return: Manifests specific to a specified repo-version.
        """
        return Manifest.objects.filter(
            pk__in=self.repo_version.content).order_by("content_ptr_id")

    class Meta:
        model = Manifest
        exclude = BaseContentResource.Meta.exclude + ("listed_manifests", )
        import_id_fields = model.natural_key_fields()
Beispiel #6
0
class CurriculumCourseResource(ModelResource):
    class Meta:
        model = CurriculumCourse
        exclude = ('created_at', 'reg_number', 'inner_id')

    id = Field(attribute='id', column_name='id', widget=UUIDWidget())
    semester_number = Field(column_name='semester',
                            attribute='semester_number')
    curriculum = fields.Field(column_name='kurikulum',
                              attribute='curriculum',
                              widget=widgets.ForeignKeyWidget(
                                  Curriculum, 'code'))
    course = fields.Field(column_name='mata_kuliah',
                          attribute='course',
                          widget=widgets.ForeignKeyWidget(Course, 'old_code'))
    name = Field(column_name='nama_mk', readonly=True)
    concentration = fields.Field(column_name='konsentrasi',
                                 attribute='concentration',
                                 widget=widgets.ManyToManyWidget(Concentration,
                                                                 separator=',',
                                                                 field='code'))
    sks_graduate = Field(column_name='min_sks_lulus', attribute='sks_graduate')

    def dehydrate_name(self, obj):
        course = getattr(obj, 'course', None)
        return '%s' % '' if not course else str(course.name)
Beispiel #7
0
class GroupResource(resources.ModelResource):
    description = fields.Field(attribute='groupprofile__description',
                               widget=widgets.PostSaveWidget(widgets.CharWidget()),
                               readonly=False)

    priority = fields.Field(attribute='groupprofile__priority',
                            widget=widgets.PostSaveWidget(widgets.IntegerWidget()),
                            readonly=False)

    can_sms_notifications = fields.Field(attribute='groupprofile__can_sms_notifications',
                                         widget=widgets.PostSaveWidget(widgets.BooleanWidget()),
                                         readonly=False)

    user_set = fields.Field(attribute='user_set',
                            widget=widgets.ManyToManyWidget(User, field='username', separator=','))

    class Meta:
        model = Group
        fields = ('id', 'name',
                  'description', 'priority', 'can_sms_notifications', 'user_set')
        export_order = ('id', 'name',
                        'description', 'priority', 'can_sms_notifications', 'user_set')

    # save userprofile related fields
    def after_post_save_instance(self, instance, row, using_transactions, dry_run):
        instance.groupprofile.save()
class AddaResource(resources.ModelResource):
    published = fields.Field(column_name='published', attribute='published')
    is_sbi_approved = fields.Field(column_name='is_sbi_approved', attribute='is_sbi_approved')
    location = fields.Field(column_name='location', attribute='location', widget=widgets.ForeignKeyWidget(Location, 'name'))
    brand = fields.Field(column_name='brand', attribute='brand', widget=widgets.ForeignKeyWidget(Brand, 'name'))
    category = fields.Field(column_name='category', attribute='category', widget=widgets.ForeignKeyWidget(Category, 'name'))
    possession = fields.Field(column_name='possession', attribute='possession', widget=widgets.ForeignKeyWidget(Possession, 'name'))
    configuration = fields.Field(column_name='configuration', attribute='configuration', widget=widgets.ManyToManyWidget(Configuration, ',', 'name'))
    fuel_type = fields.Field(column_name='fuel_type', attribute='fuel_type', widget=widgets.ForeignKeyWidget(FuelType, 'name'))
    two_wheeler_categories = fields.Field(column_name='two_wheeler_categories', attribute='two_wheeler_categories', widget=widgets.ForeignKeyWidget(TwoWheelerCategory, 'name'))
    two_wheeler_transmission = fields.Field(column_name='two_wheeler_transmission', attribute='two_wheeler_transmission', widget=widgets.ForeignKeyWidget(TwoWheelerTransmission, 'name'))
    four_wheeler_type = fields.Field(column_name='four_wheeler_type', attribute='four_wheeler_type', widget=widgets.ForeignKeyWidget(FourWheelerCategory, 'name'))
    four_wheeler_transmission = fields.Field(column_name='four_wheeler_transmission', attribute='four_wheeler_transmission', widget=widgets.ForeignKeyWidget(FourWheelerTransmission, 'name'))
    tags = fields.Field(column_name='tags', attribute='tags', widget=widgets.ManyToManyWidget(Tag, ',', 'name'))
    
    class Meta:
        model = Adda
        skip_unchanged = True
        report_skipped = False
        fields = ('id', 'title', 'published', 'is_sbi_approved', 'short_description', 'rich_text_description', 'featured_image',
                  'address', 'location', 'state', 'country', 'virtual_tour_link', 'brochure_link', 'price_sheet_link', 'market_price',
                  'brand', 'category', 'joined_users', 'favorited_users', 'possession', 'possession_date', 'configuration', 'ex_showroom_price', 'fuel_type', 'two_wheeler_categories', 'two_wheeler_transmission',
                  'two_wheeler_max_power', 'four_wheeler_type', 'four_wheeler_transmission', 'four_wheeler_bhp', 'mileage', 'tags')
        export_order = ('id', 'title', 'published', 'is_sbi_approved', 'short_description', 'rich_text_description', 'featured_image',
                        'address', 'location', 'state', 'country', 'virtual_tour_link', 'brochure_link', 'price_sheet_link', 'market_price',
                        'brand', 'category', 'joined_users', 'favorited_users', 'possession', 'possession_date', 'configuration', 'ex_showroom_price', 'fuel_type', 'two_wheeler_categories', 'two_wheeler_transmission',
                        'two_wheeler_max_power', 'four_wheeler_type', 'four_wheeler_transmission', 'four_wheeler_bhp', 'mileage', 'tags')
Beispiel #9
0
class UserResource(resources.ModelResource):
    name = fields.Field(attribute='profile__name')
    about = fields.Field(attribute='profile__about')
    organizations = fields.Field(widget=widgets.ManyToManyWidget(model=Organization, field='key'),
                                 attribute='profile__organizations')

    _profile = Profile()

    def init_instance(self, row=None):
        usr = super(UserResource, self).init_instance(row)
        usr.is_active = True
        self._profile.language = Language.objects.get(key=DEFAULT_USER_LANGUAGE)
        usr.profile = self._profile
        return usr

    def before_save_instance(self, instance, using_transactions, dry_run):
        if not using_transactions and dry_run:
            # we don't have transactions and we want to do a dry_run
            pass
        else:
            instance.set_password(instance.password)

    def after_save_instance(self, instance, using_transactions, dry_run):
        if not using_transactions and dry_run:
            # we don't have transactions and we want to do a dry_run
            pass
        else:
            Profile.objects.update_or_create(user=instance, defaults=self._profile)

    class Meta:
        model = User
        fields = ('username', 'password', 'email',)
        export_order = ('username', 'email', 'name', 'about', 'organizations')
        import_id_fields = ('username',)
Beispiel #10
0
class ServiceResource(RalphModelResource):
    profit_center = fields.Field(
        column_name='profit_center',
        attribute='profit_center',
        widget=ImportedForeignKeyWidget(assets.ProfitCenter),
    )
    business_owners = fields.Field(
        column_name='business_owners',
        attribute='business_owners',
        widget=UserManyToManyWidget(get_user_model()),
    )
    technical_owners = fields.Field(
        column_name='technical_owners',
        attribute='technical_owners',
        widget=UserManyToManyWidget(get_user_model()),
    )
    environments = ThroughField(
        column_name='environments',
        attribute='environments',
        widget=widgets.ManyToManyWidget(model=assets.Environment),
        through_model=assets.ServiceEnvironment,
        through_from_field_name='service',
        through_to_field_name='environment')

    class Meta:
        model = assets.Service
Beispiel #11
0
        class BookM2MResource(resources.ModelResource):
            categories = fields.Field(attribute='categories',
                                      widget=widgets.ManyToManyWidget(
                                          Category,
                                          field='name',
                                          separator='|'))

            class Meta:
                model = Book
Beispiel #12
0
class LogBookResource(resources.ModelResource):
    project = fields.Field(column_name='project',
                           attribute='project',
                           widget=widgets.ManyToManyWidget(Project,
                                                           field='name'))

    class Meta:
        model = LogBook
        fields = ('user', 'supervisor', 'time_used', 'comments', 'machine')
Beispiel #13
0
class EquipmentSetResource(resources.ModelResource):

    equipmentitem_set = fields.Field(attribute='equipmentitem_set',
                                     widget=widgets.ManyToManyWidget(
                                         Equipment, field='id', separator=','))

    class Meta:
        model = EquipmentSet
        fields = ('id', 'name', 'type', 'default')
        export_order = ('id', 'name', 'type', 'default')
Beispiel #14
0
class InstitutionResource(resources.ModelResource):
    tags = resources.Field(
        attribute="tags",
        column_name="tags",
        widget=widgets.ManyToManyWidget(Tag, field="name"),
    )

    class Meta:
        model = Institution
        fields = ["name", "comment", "id"]
Beispiel #15
0
class OperationResource(RalphModelResource):
    type = fields.Field(
        column_name='type',
        attribute='type',
        widget=ImportedForeignKeyWidget(OperationType),
    )
    base_objects = fields.Field(
        column_name='base_objects',
        attribute='base_objects',
        widget=widgets.ManyToManyWidget(model=base.BaseObject),
        default=[],
    )
    assignee = fields.Field(
        column_name='assignee',
        attribute='assignee',
        widget=UserWidget(get_user_model()),
    )
    reporter = fields.Field(
        column_name='reporter',
        attribute='reporter',
        widget=UserWidget(get_user_model()),
    )
    service_name = fields.Field(
        column_name='base_objects_service_names',
        attribute='base_objects',
        widget=BaseObjectServiceNamesM2MWidget(model=base.BaseObject),
        default=[],
        readonly=True
    )
    service_name._skip_str_field = True

    class Meta:
        select_related = (
            'assignee', 'reporter', 'type', 'status'
        )
        prefetch_related = (
            'tags',
            Prefetch(
                lookup='base_objects',
                queryset=BaseObject.polymorphic_objects.polymorphic_filter(
                    operations__in=Operation.objects.all()
                ).select_related(
                    'service_env',
                    'service_env__service',
                    'service_env__environment'
                ).polymorphic_select_related(
                    Cluster=['type'],
                    ServiceEnvironment=['service', 'environment']
                )
            )
        )
        model = Operation
Beispiel #16
0
class EntityAttrResource(AironeModelResource):
    _IMPORT_INFO = {
        'header': [
            'id', 'name', 'type', 'refer', 'entity', 'created_user',
            'is_mandatory'
        ],
        'mandatory_keys': ['name', 'type', 'entity', 'created_user'],
        'resource_module':
        'entity.admin',
        'resource_model_name':
        'EntityAttrResource',
    }

    COMPARING_KEYS = [
        'name', 'is_mandatory', 'referral', 'parent_entity', 'created_user'
    ]
    DISALLOW_UPDATE_KEYS = ['parent_entity', 'created_user']

    user = fields.Field(column_name='created_user',
                        attribute='created_user',
                        widget=widgets.ForeignKeyWidget(User, 'username'))
    refer = fields.Field(column_name='refer',
                         attribute='referral',
                         widget=widgets.ManyToManyWidget(model=ACLBase,
                                                         field='name'))
    entity = fields.Field(column_name='entity',
                          attribute='parent_entity',
                          widget=widgets.ForeignKeyWidget(model=Entity,
                                                          field='name'))

    class Meta:
        model = EntityAttr
        fields = ('id', 'name', 'type', 'is_mandatory')

    def after_save_instance(self, instance, using_transactions, dry_run):
        # If a new EntityAttr object is created,
        # this processing append it to the associated Entity object.
        if not dry_run:
            entity = instance.parent_entity

            if not entity.attrs.filter(id=instance.id).exists():
                entity.attrs.add(instance)

    def import_obj(self, instance, data, dry_run):
        if not Entity.objects.filter(name=data['entity']).exists():
            raise RuntimeError('failed to identify entity object')

        if data['refer'] and not Entity.objects.filter(
                name=data['refer']).exists():
            raise RuntimeError('refer to invalid entity object')

        super(EntityAttrResource, self).import_obj(instance, data, dry_run)
Beispiel #17
0
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)
Beispiel #18
0
class RosterResource(resources.ModelResource):
    user_name = fields.Field(column_name='User Name',
                             attribute='user',
                             widget=widgets.ForeignKeyWidget(
                                 auth.models.User, 'username'))
    semester_name = fields.Field(column_name='Semester Name',
                                 attribute='semester',
                                 widget=widgets.ForeignKeyWidget(
                                     core.models.Semester, 'name'))
    unit_list = fields.Field(column_name='Unit List',
                             attribute='curriculum',
                             widget=widgets.ManyToManyWidget(core.models.Unit,
                                                             separator=';'))
Beispiel #19
0
class ProductResource(resources.ModelResource):

    class Meta:
        model = Product
        exclude = ('parent', 'slug', 'modified', 'lft', 'rght', 'tree_id', 'level')

    title = Field(attribute='title', column_name='Title')
    slug = Field(attribute='slug', column_name='slug')
    short_description = Field(attribute='short_description', column_name='short_description')
    general_description = Field(attribute='general_description', column_name='general_description')
    func_description = Field(attribute='func_description', column_name='func_description')
    tech_description = Field(attribute='tech_description', column_name='tech_description')
    meta_keywords = Field(attribute='meta_keywords', column_name='meta_keywords')
    meta_description = Field(attribute='meta_description', column_name='meta_description')
    qualifier = Field(attribute='qualifier', column_name='qualifier')
    rub_price = Field()
    usd_price = Field()
    eur_price = Field()
    prices = Field(
        attribute='prices',
        widget=widgets.ManyToManyWidget(
            ProductXCurrency,
            field='price',
            separator='|')
    )

    def save(self, commit=True):
        rub_price = self.cleaned_data.get('rub_price', None)
        # ...do something with extra_field here...
        return super(ProductResource, self).save(commit=commit)

    def dehydrate_rub_price(self, product: Product):
        rub_price = product.prices.filter(currency_id='RUB').first()
        return getattr(rub_price, 'price', '-')

    def dehydrate_usd_price(self, product: Product):
        usd_price = product.prices.filter(currency_id='USD').first()
        return getattr(usd_price, 'price', '-')

    def dehydrate_eur_price(self, product: Product):
        eur_price = product.prices.filter(currency_id='EUR').first()
        return getattr(eur_price, 'price', '-')
Beispiel #20
0
class DCHostResource(RalphModelResource):
    hostname = fields.Field(
        readonly=True,
        column_name='hostname',
        attribute='hostname',
    )
    service_env = fields.Field(
        column_name='service_env',
        attribute='service_env',
        widget=AssetServiceEnvWidget(assets.ServiceEnvironment, 'name'),
    )
    ips = fields.Field(
        column_name='ip_addresses',
        attribute='ipaddresses',
        widget=widgets.ManyToManyWidget(model=networks.IPAddress),
    )

    class Meta:
        model = hosts.DCHost
        exclude = ('parent', )
Beispiel #21
0
class StudentIEResource(RosterResource):
    semester_name = fields.Field(column_name='Semester Name',
                                 attribute='semester',
                                 widget=widgets.ForeignKeyWidget(
                                     Semester, 'name'))
    unit_list = fields.Field(column_name='Unit List',
                             attribute='curriculum',
                             widget=widgets.ManyToManyWidget(Unit,
                                                             separator=';'))

    class Meta:
        skip_unchanged = True
        model = Student
        fields = (
            'id',
            'user__first_name',
            'user__last_name',
            'user__email',
            'semester_name',
            'user_name',
            'track',
            'legit',
        )
        export_order = fields
Beispiel #22
0
class TeacherResource(ModelResource):
    class Meta:
        model = Teacher
        fields = ('id', 'account', 'tid', 'rmu', 'courses', 'is_active')

    id = Field(attribute='id', column_name='id', widget=UUIDWidget())
    name = Field(column_name='name', readonly=True)
    tid = Field(column_name='nidn', attribute='tid')
    account = fields.Field(column_name='email_account',
                           attribute='account',
                           widget=widgets.ForeignKeyWidget(
                               get_user_model(), 'email'))
    rmu = fields.Field(column_name='program_studi',
                       attribute='rmu',
                       widget=widgets.ForeignKeyWidget(ManagementUnit, 'code'))
    courses = fields.Field(column_name='mata_kuliah',
                           attribute='courses',
                           widget=widgets.ManyToManyWidget(Course,
                                                           separator=',',
                                                           field='old_code'))

    def dehydrate_name(self, obj):
        account = getattr(obj, 'account', None)
        return '%s' % account
Beispiel #23
0
 def setUp(self):
     self.widget = widgets.ManyToManyWidget(Category)
     self.widget_name = widgets.ManyToManyWidget(Category, field="name")
     self.cat1 = Category.objects.create(name=u'Cat úňíčóďě')
     self.cat2 = Category.objects.create(name='Cat 2')
Beispiel #24
0
class EntityAttrResource(AironeModelResource):
    _IMPORT_INFO = {
        "header": [
            "id",
            "name",
            "type",
            "refer",
            "entity",
            "created_user",
            "is_mandatory",
        ],
        "mandatory_keys": ["name", "entity", "created_user"],
        "resource_module":
        "entity.admin",
        "resource_model_name":
        "EntityAttrResource",
    }

    COMPARING_KEYS = [
        "name",
        "is_mandatory",
        "referral",
        "parent_entity",
        "created_user",
    ]
    DISALLOW_UPDATE_KEYS = ["parent_entity", "created_user"]

    user = fields.Field(
        column_name="created_user",
        attribute="created_user",
        widget=widgets.ForeignKeyWidget(User, "username"),
    )
    refer = fields.Field(
        column_name="refer",
        attribute="referral",
        widget=widgets.ManyToManyWidget(model=Entity, field="name"),
    )
    entity = fields.Field(
        column_name="entity",
        attribute="parent_entity",
        widget=widgets.ForeignKeyWidget(model=Entity, field="name"),
    )

    class Meta:
        model = EntityAttr
        fields = ("id", "name", "type", "is_mandatory")

    def after_save_instance(self, instance, using_transactions, dry_run):
        # If a new EntityAttr object is created,
        # this processing append it to the associated Entity object.
        if not dry_run:
            entity = instance.parent_entity

            if not entity.attrs.filter(id=instance.id).exists():
                entity.attrs.add(instance)

    def import_obj(self, instance, data, dry_run):
        if not Entity.objects.filter(name=data["entity"]).exists():
            raise RuntimeError("failed to identify entity object")

        if data["refer"] and not all([
                Entity.objects.filter(name=x).exists()
                for x in data["refer"].split(",")
        ]):
            raise RuntimeError("refer to invalid entity object")

        # The processing fails when 'type' parameter is not existed for creating a new instance
        if not instance.pk and not data["type"]:
            raise RuntimeError(
                "The parameter 'type' is mandatory when a new EntityAtter create"
            )

        # Set event handler for custom-view. When it returns not None, then it abort to import.
        if custom_view.is_custom("import_entity_attr"):
            error = custom_view.call_custom("import_entity_attr", None,
                                            instance, data)
            if error:
                raise RuntimeError(error)

        # Do not allow to change type when instance is already created
        if instance.pk:
            data["type"] = instance.type

        super(EntityAttrResource, self).import_obj(instance, data, dry_run)
Beispiel #25
0
 def setUp(self):
     self.widget = widgets.ManyToManyWidget(Category)
     self.cat1 = Category.objects.create(name='Cat 1')
     self.cat2 = Category.objects.create(name='Cat 2')
Beispiel #26
0
class EntityAttrResource(AironeModelResource):
    _IMPORT_INFO = {
        'header': [
            'id', 'name', 'type', 'refer', 'entity', 'created_user',
            'is_mandatory'
        ],
        'mandatory_keys': ['name', 'entity', 'created_user'],
        'resource_module':
        'entity.admin',
        'resource_model_name':
        'EntityAttrResource',
    }

    COMPARING_KEYS = [
        'name', 'is_mandatory', 'referral', 'parent_entity', 'created_user'
    ]
    DISALLOW_UPDATE_KEYS = ['parent_entity', 'created_user']

    user = fields.Field(column_name='created_user',
                        attribute='created_user',
                        widget=widgets.ForeignKeyWidget(User, 'username'))
    refer = fields.Field(column_name='refer',
                         attribute='referral',
                         widget=widgets.ManyToManyWidget(model=Entity,
                                                         field='name'))
    entity = fields.Field(column_name='entity',
                          attribute='parent_entity',
                          widget=widgets.ForeignKeyWidget(model=Entity,
                                                          field='name'))

    class Meta:
        model = EntityAttr
        fields = ('id', 'name', 'type', 'is_mandatory')

    def after_save_instance(self, instance, using_transactions, dry_run):
        # If a new EntityAttr object is created,
        # this processing append it to the associated Entity object.
        if not dry_run:
            entity = instance.parent_entity

            if not entity.attrs.filter(id=instance.id).exists():
                entity.attrs.add(instance)

    def import_obj(self, instance, data, dry_run):
        if not Entity.objects.filter(name=data['entity']).exists():
            raise RuntimeError('failed to identify entity object')

        if data['refer'] and not all([
                Entity.objects.filter(name=x).exists()
                for x in data['refer'].split(',')
        ]):
            raise RuntimeError('refer to invalid entity object')

        # The processing fails when 'type' parameter is not existed for creating a new instance
        if not instance.pk and not data['type']:
            raise RuntimeError(
                "The parameter 'type' is mandatory when a new EntityAtter create"
            )

        # Set event handler for custom-view. When it returns not None, then it abort to import.
        if custom_view.is_custom('import_entity_attr'):
            error = custom_view.call_custom('import_entity_attr', None,
                                            instance, data)
            if error:
                raise RuntimeError(error)

        # Do not allow to change type when instance is already created
        if instance.pk:
            data['type'] = instance.type

        super(EntityAttrResource, self).import_obj(instance, data, dry_run)
Beispiel #27
0
class ProductResource(VerboseNameModelResource):
    brand = Field(attribute='brand',
                  column_name='Бренд',
                  widget=widgets.ForeignKeyWidget(Brand, field='code'))

    enable = Field(attribute='enable',
                   column_name='Показывать',
                   widget=MyBooleanWidget())

    categories = Field(attribute='categories',
                       column_name='Категории',
                       widget=widgets.ManyToManyWidget(Category,
                                                       field='full_name',
                                                       separator='\n'))

    description = TranslatableField(attribute='description',
                                    column_name="Описание",
                                    widget=widgets.JSONWidget(),
                                    saves_null_values=False)

    content = TranslatableField(attribute='content',
                                column_name="Состав",
                                widget=widgets.JSONWidget(),
                                saves_null_values=False)

    thumbnail = Field(
        attribute='thumbnail',
        column_name='Превью',
        # widget=widgets.ForeignKeyWidget(MediaFile, field='link')
        widget=MyGetForeignKeyWidget(MediaFile, field='link'))

    media_files = Field(
        attribute='media_files',
        column_name='Медиа файлы',
        # widget=widgets.ManyToManyWidget(MediaFile, field='link', separator='\n')
        widget=MyGetManyToManyWidget(MediaFile, field='link', separator='\n'))

    video_files = Field(
        attribute='video_files',
        column_name='Видео',
        # widget=widgets.ManyToManyWidget(MediaFile, field='link', separator='\n')
        widget=MyGetManyToManyWidget(MediaFile, field='link', separator='\n'))

    def get_locales(self, product, order=("ru", "en")):
        available_locales = product.get_available_languages(
            include_unsaved=True)
        export_order = order + tuple(
            l for l in available_locales if l not in order)
        return [l for l in export_order if l in available_locales]

    def dehydrate_description(self, product):
        return {
            loc: product.safe_translation_getter('description',
                                                 language_code=loc)
            for loc in self.get_locales(product)
        }

    def dehydrate_content(self, product):
        return {
            loc: product.safe_translation_getter('content', language_code=loc)
            for loc in self.get_locales(product)
        }

    class Meta:
        model = Product
        skip_unchanged = False
        report_skipped = True
        import_id_fields = ('sku', )
        exclude = ('id', )
        widgets = {
            'pub_date': {
                'format': '%d.%m.%y %H:%M'
            },
            'mod_date': {
                'format': '%d.%m.%y %H:%M'
            },
        }

        fields = (
            'sku',
            'model',
            'brand',
            'enable',
            'categories',
            'description',
            'content',
            'thumbnail',
            'media_files',
            'video_files',
            'price',
        )

        export_order = fields
Beispiel #28
0
class AttrValueResource(AironeModelResource):
    _IMPORT_INFO = {
        "header": [
            "id",
            "refer",
            "value",
            "attribute_id",
            "created_time",
            "created_user",
            "status",
            "data_arr",
        ],
        "mandatory_keys": ["id", "attribute_id", "created_user", "status"],
        "resource_module": "entry.admin",
        "resource_model_name": "AttrValueResource",
    }
    COMPARING_KEYS = []
    DISALLOW_UPDATE_KEYS = [
        "created_time",
        "created_user",
        "parent_attr",
        "value",
        "referral",
        "status",
    ]

    attr_id = fields.Field(
        column_name="attribute_id",
        attribute="parent_attr",
        widget=widgets.ForeignKeyWidget(model=Attribute, field="id"),
    )
    refer = fields.Field(
        column_name="refer",
        attribute="referral",
        widget=widgets.ForeignKeyWidget(model=ACLBase, field="id"),
    )
    user = fields.Field(
        column_name="created_user",
        attribute="created_user",
        widget=widgets.ForeignKeyWidget(User, "username"),
    )
    data_arr = fields.Field(
        column_name="data_arr",
        attribute="data_array",
        widget=widgets.ManyToManyWidget(model=AttributeValue, field="id"),
    )

    class Meta:
        model = AttributeValue
        fields = ("id", "name", "value", "created_time", "status")
        skip_unchanged = True
        instance_loader_class = CachedInstanceLoader

    def after_save_instance(self, instance, using_transactions, dry_run):
        # If a new AttributeValue object is created,
        # this processing append it to the associated Entity object.
        self._saved_instance = None
        if not dry_run:
            attr = instance.parent_attr

            # register data_type parameter which is same with EntityAttr's type
            instance.data_type = attr.schema.type

            if not attr.values.filter(id=instance.id).exists() and (
                not attr.schema.type & AttrTypeValue["array"]
                or (
                    attr.schema.type & AttrTypeValue["array"]
                    and instance.get_status(AttributeValue.STATUS_DATA_ARRAY_PARENT)
                )
            ):

                # clear is_latest flag of old attrs and set it to new one.
                instance.is_latest = True
                attr.values.add(instance)
                attr.unset_latest_flag(exclude_id=instance.id)

            # the case of leaf AttributeValue
            elif attr.schema.type & AttrTypeValue["array"] and not instance.get_status(
                AttributeValue.STATUS_DATA_ARRAY_PARENT
            ):

                # For a leaf AttributeValue, 'is_latest' flag will not be set.
                # Instaed, these objects have
                # parent_attrv parameter to identify parent AttributeValue.
                instance.is_latest = False
                instance.parent_attrv = attr.get_latest_value()

            instance.save(update_fields=["is_latest", "data_type", "parent_attrv"])
            self._saved_instance = instance
            attr.parent_entry.register_es()

    @classmethod
    def after_import_completion(self, results):
        # make relation between the array of AttributeValue
        for data in [
            x["data"]
            for x in results
            if x["data"]["status"] & AttributeValue.STATUS_DATA_ARRAY_PARENT
        ]:

            attr_value = AttributeValue.objects.get(id=data["id"])
            for child_id in [int(x) for x in data["data_arr"].split(",")]:
                if (
                    AttributeValue.objects.filter(id=child_id).exists()
                    and not attr_value.data_array.filter(id=child_id).exists()
                ):

                    # append related AttributeValue if it's not existed
                    attr_value.data_array.add(AttributeValue.objects.get(id=child_id))

            attr_value.parent_attr.parent_entry.register_es()
Beispiel #29
0
class AttrValueResource(AironeModelResource):
    _IMPORT_INFO = {
        'header': [
            'id', 'refer', 'value', 'attribute_id', 'created_time',
            'created_user', 'status', 'data_arr'
        ],
        'mandatory_keys': ['id', 'attribute_id', 'created_user', 'status'],
        'resource_module':
        'entry.admin',
        'resource_model_name':
        'AttrValueResource',
    }
    COMPARING_KEYS = []
    DISALLOW_UPDATE_KEYS = [
        'created_time', 'created_user', 'parent_attr', 'value', 'referral',
        'status'
    ]

    attr_id = fields.Field(column_name='attribute_id',
                           attribute='parent_attr',
                           widget=widgets.ForeignKeyWidget(model=Attribute,
                                                           field='id'))
    refer = fields.Field(column_name='refer',
                         attribute='referral',
                         widget=widgets.ForeignKeyWidget(model=ACLBase,
                                                         field='id'))
    user = fields.Field(column_name='created_user',
                        attribute='created_user',
                        widget=widgets.ForeignKeyWidget(User, 'username'))
    data_arr = fields.Field(column_name='data_arr',
                            attribute='data_array',
                            widget=widgets.ManyToManyWidget(
                                model=AttributeValue, field='id'))

    class Meta:
        model = AttributeValue
        fields = ('id', 'name', 'value', 'created_time', 'status')
        skip_unchanged = True
        instance_loader_class = CachedInstanceLoader

    def after_save_instance(self, instance, using_transactions, dry_run):
        # If a new AttributeValue object is created,
        # this processing append it to the associated Entity object.
        self._saved_instance = None
        if not dry_run:
            attr = instance.parent_attr

            # register data_type parameter which is same with EntityAttr's type
            instance.data_type = attr.schema.type

            if (not attr.values.filter(id=instance.id).exists()
                    and (not attr.schema.type & AttrTypeValue['array'] or
                         (attr.schema.type & AttrTypeValue['array']
                          and instance.get_status(
                              AttributeValue.STATUS_DATA_ARRAY_PARENT)))):

                # clear is_latest flag of old attrs and set it to new one.
                instance.is_latest = True
                attr.values.add(instance)
                attr.unset_latest_flag(exclude_id=instance.id)

            # the case of leaf AttributeValue
            elif (attr.schema.type & AttrTypeValue['array']
                  and not instance.get_status(
                      AttributeValue.STATUS_DATA_ARRAY_PARENT)):

                # For a leaf AttributeValue, 'is_latest' flag will not be set.
                # Instaed, these objects have
                # parent_attrv parameter to identify parent AttributeValue.
                instance.is_latest = False
                instance.parent_attrv = attr.get_latest_value()

            instance.save(
                update_fields=['is_latest', 'data_type', 'parent_attrv'])
            self._saved_instance = instance
            attr.parent_entry.register_es()

    @classmethod
    def after_import_completion(self, results):
        # make relation between the array of AttributeValue
        for data in [
                x['data'] for x in results if x['data']['status']
                & AttributeValue.STATUS_DATA_ARRAY_PARENT
        ]:

            attr_value = AttributeValue.objects.get(id=data['id'])
            for child_id in [int(x) for x in data['data_arr'].split(',')]:
                if (AttributeValue.objects.filter(id=child_id).exists()
                        and not attr_value.data_array.filter(
                            id=child_id).exists()):

                    # append related AttributeValue if it's not existed
                    attr_value.data_array.add(
                        AttributeValue.objects.get(id=child_id))

            attr_value.parent_attr.parent_entry.register_es()