class TaskTemplateFilter(FilterSet): label_ids = filters.CharFilter(method="filter_by_label_ids") subprocess_has_update = filters.BooleanFilter( method="filter_subprocess_has_update") has_subprocess = filters.BooleanFilter( field_name="pipeline_template__has_subprocess") def filter_by_label_ids(self, query, name, value): label_ids = [int(label_id) for label_id in value.strip().split(",")] template_ids = list( TemplateLabelRelation.objects. fetch_template_ids_using_union_labels(label_ids)) condition = Q(id__in=template_ids) return query.filter(condition) def filter_subprocess_has_update(self, query, name, value): pipeline_template_ids = set( query.values_list("pipeline_template_id", flat=True)) pipeline_template = PipelineTemplate.objects.filter( template_id__in=pipeline_template_ids) condition = [ item.template_id for item in pipeline_template if item.subprocess_has_update == value ] return query.filter(pipeline_template_id__in=condition) class Meta: model = TaskTemplate # 模型名 fields = { "pipeline_template__name": ["icontains"], "pipeline_template__edit_time": ["gte", "lte"], "pipeline_template__creator": ["contains"], "project_id": ["exact"], "category": ["exact"] }
class AlbumFilter(filterset.FilterSet, TagsFilterMixin): published_date__lte = filters.DateTimeFilter(field_name="published_date", lookup_expr="lte") published_date__gte = filters.DateTimeFilter(field_name="published_date", lookup_expr="gte") public = filters.BooleanFilter(field_name="public") query = WatsonFilter()
class F(FilterSet): """ BOOL FILTER """ """Filter for Books by if books are published or not""" check_params = filters.BooleanFilter( name='check_params') #, method='params_checked') username = filters2.CharFilter(field_name='username') # def params_checked(self, queryset, name, value): # # construct the full lookup expression. # lookup = '__'.join([name, 'isnull']) # return queryset.filter(**{lookup: False}) # # alternatively, it may not be necessary to construct the lookup. # return queryset.filter(published_on__isnull=False) class Meta: model = models.Employee fields = ['check_params', 'username'] # class Author_by_paper_title_Filter(filters.FilterSet): # title = filters.AllLookupsFilter() # author__name = filters.CharFilter(field_name='author__name', lookup_expr='startswith') # # class Meta: # model = models.Paper # fields = []
class MeasurementFilter(filters.FilterSet): active = django_filters.BooleanFilter(name='active') created_before = django_filters.IsoDateTimeFilter( name='update_ref__mod_time', lookup_expr='lte', ) created_after = django_filters.IsoDateTimeFilter( name='update_ref__mod_time', lookup_expr='gte', ) compartment = django_filters.ChoiceFilter( name='compartment', choices=models.Measurement.Compartment.CHOICE, ) line = django_filters.ModelChoiceFilter( name='assay__line', queryset=models.Line.objects.all(), ) measurement_format = django_filters.ChoiceFilter( name='measurement_format', choices=models.Measurement.Format.CHOICE, ) class Meta: model = models.Measurement fields = { 'assay': ['exact', 'in'], 'measurement_type': ['exact', 'in'], 'x_units': ['exact', 'in'], 'y_units': ['exact', 'in'] }
class MeasurementFilter(filters.FilterSet): active = django_filters.BooleanFilter(field_name="active") created_before = django_filters.IsoDateTimeFilter( field_name="update_ref__mod_time", lookup_expr="lte" ) created_after = django_filters.IsoDateTimeFilter( field_name="update_ref__mod_time", lookup_expr="gte" ) compartment = django_filters.ChoiceFilter( field_name="compartment", choices=models.Measurement.Compartment.CHOICE ) line = django_filters.ModelChoiceFilter( field_name="assay__line", queryset=models.Line.objects.all() ) measurement_format = django_filters.ChoiceFilter( field_name="measurement_format", choices=models.Measurement.Format.CHOICE ) class Meta: model = models.Measurement fields = { "assay": ["exact", "in"], "measurement_type": ["exact", "in"], "x_units": ["exact", "in"], "y_units": ["exact", "in"], }
class ReportFilter(FilterSet): current = filters.BooleanFilter(field_name='current') user = filters.CharFilter(field_name='user') class Meta: model = Report fields = ['current']
def __init__(self, *args, **kwargs): super(FilterSet, self).__init__(*args, **kwargs) for name, filter_ in six.iteritems(self.filters): if isinstance(filter_, filters.RelatedFilter): # Populate our FilterSet fields with the fields we've stored # in RelatedFilter. filter_.setup_filterset() self.populate_from_filterset(filter_.filterset, filter_, name) # Add an 'isnull' filter to allow checking if the relation is empty. isnull_filter = filters.BooleanFilter( name=("%s%sisnull" % (filter_.name, LOOKUP_SEP))) self.filters['%s%s%s' % (filter_.name, LOOKUP_SEP, 'isnull')] = isnull_filter elif isinstance(filter_, filters.AllLookupsFilter): # Populate our FilterSet fields with all the possible # filters for the AllLookupsFilter field. model = self._meta.model field = get_model_field(model, filter_.name) for lookup_type in self.LOOKUP_TYPES: if isinstance(field, RelatedObject): f = self.filter_for_reverse_field(field, filter_.name) else: f = self.filter_for_field(field, filter_.name) f.lookup_type = lookup_type f = self.fix_filter_field(f) self.filters["%s%s%s" % (name, LOOKUP_SEP, lookup_type)] = f
class CollectionVersionFilter(ContentFilter): """ FilterSet for Ansible CollectionVersions. """ namespace = filters.CharFilter(field_name="namespace") name = filters.CharFilter(field_name="name") is_highest = filters.BooleanFilter(field_name="is_highest") q = filters.CharFilter(field_name="q", method="filter_by_q") tags = filters.CharFilter( field_name="tags", method="filter_by_tags", help_text=_( "Filter by comma separate list of tags that must all be matched"), ) def filter_by_q(self, queryset, name, value): """ Full text search provided by the 'q' option. Args: queryset: The query to add the additional full-text search filtering onto name: The name of the option specified, i.e. 'q' value: The string to search on Returns: The Django queryset that was passed in, additionally filtered by full-text search. """ search_query = SearchQuery(value) qs = queryset.filter(search_vector=search_query) ts_rank_fn = Func( F("search_vector"), search_query, 32, # RANK_NORMALIZATION = 32 function="ts_rank", output_field=db_fields.FloatField(), ) return qs.annotate(rank=ts_rank_fn).order_by("-rank") def filter_by_tags(self, qs, name, value): """ Filter queryset qs by list of tags. Args: qs (django.db.models.query.QuerySet): CollectionVersion queryset value (string): A comma separated list of tags Returns: Queryset of CollectionVersion that matches all tags """ for tag in value.split(","): qs = qs.filter(tags__name=tag) return qs class Meta: model = CollectionVersion fields = ["namespace", "name", "version", "q", "is_highest", "tags"]
def fix_filter_field(self, f): """ Fix the filter field based on the lookup type. """ lookup_type = f.lookup_type if lookup_type == 'isnull': return filters.BooleanFilter(name=("%s%sisnull" % (f.name, LOOKUP_SEP))) return f
def fix_filter_field(self, f): """ Fix the filter field based on the lookup type. """ lookup_type = f.lookup_type if lookup_type == 'isnull': return filters.BooleanFilter(name=("%s%sisnull" % (f.name, LOOKUP_SEP))) if lookup_type == 'in' and type(f) in [filters.NumberFilter]: return filters.InSetNumberFilter(name=("%s%sin" % (f.name, LOOKUP_SEP))) return f
class EDDObjectFilter(filters.FilterSet): active = django_filters.BooleanFilter(name='active') created_before = django_filters.IsoDateTimeFilter(name='created__mod_time', lookup_expr='lte') created_after = django_filters.IsoDateTimeFilter(name='created__mod_time', lookup_expr='gte') description = django_filters.CharFilter(name='description', lookup_expr='iregex') name = django_filters.CharFilter(name='name', lookup_expr='iregex') updated_before = django_filters.IsoDateTimeFilter(name='updated__mod_time', lookup_expr='lte') updated_after = django_filters.IsoDateTimeFilter(name='updated__mod_time', lookup_expr='gte') class Meta: model = models.EDDObject fields = []
class EDDObjectFilter(filters.FilterSet): active = django_filters.BooleanFilter( field_name="active", help_text= _("Filter on currently active/visible items (True/1/yes or false/0/no)" ), ) created_before = django_filters.IsoDateTimeFilter( field_name="created__mod_time", help_text=_("Use an ISO-8601-like datetime: 2020-01-01 00:00:00"), lookup_expr="lte", ) created_after = django_filters.IsoDateTimeFilter( field_name="created__mod_time", help_text=_("Use an ISO-8601-like datetime: 2020-01-01 00:00:00"), lookup_expr="gte", ) description = django_filters.CharFilter( field_name="description", help_text=_("Runs a regular expression search on item description"), lookup_expr="iregex", ) name = django_filters.CharFilter( field_name="name", help_text=_("Runs a regular expression search on item name"), lookup_expr="iregex", ) updated_before = django_filters.IsoDateTimeFilter( field_name="updated__mod_time", help_text=_("Use an ISO-8601-like datetime: 2020-01-01 00:00:00"), lookup_expr="lte", ) updated_after = django_filters.IsoDateTimeFilter( field_name="updated__mod_time", help_text=_("Use an ISO-8601-like datetime: 2020-01-01 00:00:00"), lookup_expr="gte", ) class Meta: model = models.EDDObject fields = [] @classmethod def truthy(cls, value): """ Utility to check if a string filter value is Boolean True for filtering. Accepts case-insensitive "true", "yes", "t", "y", "1" as True. All other values are treated as False. """ return str(value).lower() in {"true", "t", "yes", "y", "1"}
class IngeschrevenPersoonFilter(FilterSet): burgerservicenummer = filters.CharFilter() geboorte__datum = filters.CharFilter() geboorte__plaats = filters.CharFilter() geslachtsaanduiding = filters.CharFilter() # Add enum inclusiefoverledenpersonen = filters.BooleanFilter() naam__geslachtsnaam = filters.CharFilter() naam__voornamen = filters.CharFilter() verblijfplaats__gemeentevaninschrijving = filters.CharFilter() verblijfplaats__huisletter = filters.CharFilter() verblijfplaats__huisnummer = filters.NumberFilter() verblijfplaats__huisnummertoevoeging = filters.CharFilter() verblijfplaats__identificatiecodenummeraanduiding = filters.CharFilter() verblijfplaats__naamopenbareruimte = filters.CharFilter() verblijfplaats__postcode = filters.CharFilter() naam__voorvoegsel = filters.CharFilter()
class DoctorFilter(FilterSet): # user doctors can be done throught https://django-filter.readthedocs.io/en/stable/ref/filters.html#method userDoctors = filters.BooleanFilter(field_name="userDoctors", method="filter_user_doctors") name = CharFilter(field_name="name", lookup_expr="contains") surname = CharFilter(field_name="surname", lookup_expr="contains") class Meta: model = Doctor fields = ['sex', 'name', 'surname'] def filter_user_doctors(self, queryset, name, value): if value: queryset = queryset.filter( patients__in=[get_user_by_type(self.request.user)]) return queryset
class EDDObjectFilter(filters.FilterSet): active = django_filters.BooleanFilter(field_name="active") created_before = django_filters.IsoDateTimeFilter( field_name="created__mod_time", lookup_expr="lte") created_after = django_filters.IsoDateTimeFilter( field_name="created__mod_time", lookup_expr="gte") description = django_filters.CharFilter(field_name="description", lookup_expr="iregex") name = django_filters.CharFilter(field_name="name", lookup_expr="iregex") updated_before = django_filters.IsoDateTimeFilter( field_name="updated__mod_time", lookup_expr="lte") updated_after = django_filters.IsoDateTimeFilter( field_name="updated__mod_time", lookup_expr="gte") class Meta: model = models.EDDObject fields = []
class HeroFilterSet(FilterSet): user_name = filters.CharFilter(field_name='user__username') find_opponents_for = filters.ModelChoiceFilter( method='get_available_opponents', label="find opponents for", queryset=Hero.objects.all()) is_alive = filters.BooleanFilter(label='is alive') class Meta: model = Hero fields = ('user_name', 'race', 'guild', 'is_alive', 'find_opponents_for') def get_available_opponents(self, queryset, name, value: Hero): available_heroes = Hero.objects.get_annotations().filter( is_alive=True, race__in=value.race.can_fight_with.all()).exclude( user=value.user).exclude(battles__in=value.battles.all()) return available_heroes
class CollectionFilter(BaseFilterSet): """ FilterSet for Ansible Collections. """ namespace = filters.CharFilter(field_name="namespace") name = filters.CharFilter(field_name="name") deprecated = filters.BooleanFilter(field_name="deprecated", method="get_deprecated") def get_deprecated(self, qs, name, value): """Deprecated filter.""" deprecation = self.request.parser_context["view"]._deprecation if value and deprecation: return qs.filter(pk__in=deprecation) if value is False and deprecation: return qs.exclude(pk__in=deprecation) return qs class Meta: model = Collection fields = ["namespace", "name", "deprecated"]
class LearningUnitDescriptionFicheFilter(FilterSet): academic_year = filters.ModelChoiceFilter( queryset=AcademicYear.objects.all(), required=True, label=_('Ac yr.')) acronym = filters.CharFilter( field_name="acronym", lookup_expr='icontains', max_length=40, required=False, label=_('Code'), ) learning_unit_title = filters.CharFilter( field_name='full_title', lookup_expr='icontains', label=_('Title'), ) container_type = filters.ChoiceFilter( field_name='learning_container_year__container_type', choices=LearningContainerYearType.choices() + ((MOBILITY, _('Mobility')), ), label=_('Type'), empty_label=pgettext_lazy("plural", "All")) subtype = filters.ChoiceFilter( choices=learning_unit_year_subtypes.LEARNING_UNIT_YEAR_SUBTYPES, label=_('Subtype'), empty_label=pgettext_lazy("plural", "All")) status = filters.TypedChoiceFilter( choices=(('', _("All")), ('true', _("Active")), ('false', _("Inactive"))), label=_('Status'), coerce=strtobool, ) quadrimester = filters.ChoiceFilter( choices=quadrimesters.LEARNING_UNIT_YEAR_QUADRIMESTERS, label=_('Quadri'), empty_label=pgettext_lazy("plural", "All")) tutor = filters.CharFilter( method='filter_tutor', label=_('Tutor'), ) requirement_entity = filters.CharFilter( method='filter_requirement_entity_with_entity_subordinated', label=_('Req. Entity')) allocation_entity = filters.CharFilter( method='filter_allocation_entity_with_entity_subordinated', label=_('Alloc. Ent.')) with_entity_subordinated = filters.BooleanFilter( method=lambda queryset, *args, **kwargs: queryset, label=_('Include subordinate entities'), widget=forms.CheckboxInput) class Meta: model = LearningUnitYear fields = [] def __init__(self, data=None, queryset=None, *, request=None, prefix=None): translated_text_qs = TranslatedText.objects.filter( entity=LEARNING_UNIT_YEAR, text_label__label__in=CMS_LABEL_PEDAGOGY, changed__isnull=False, reference=OuterRef('pk')).order_by("-changed") queryset = LearningUnitYear.objects.all().annotate( full_title=Case( When(Q(learning_container_year__common_title__isnull=True) | Q(learning_container_year__common_title__exact=''), then='specific_title'), When(Q(specific_title__isnull=True) | Q(specific_title__exact=''), then='learning_container_year__common_title'), default=Concat('learning_container_year__common_title', Value(' - '), 'specific_title'), output_field=CharField(), ), last_translated_text_changed=Subquery( translated_text_qs.values('changed')[:1]), ) super(LearningUnitDescriptionFicheFilter, self).__init__( data=data, queryset=queryset, request=request, prefix=prefix, ) self.form.fields['academic_year'].initial = starting_academic_year() self.form.fields['with_entity_subordinated'].initial = True def filter_tutor(self, queryset, name, value): return queryset.filter( Q(learningcomponentyear__attributionchargenew__attribution__tutor__person__first_name__icontains =value) | Q(learningcomponentyear__attributionchargenew__attribution__tutor__person__last_name__icontains =value)) def filter_requirement_entity_with_entity_subordinated( self, queryset, name, value): with_subordinated = self.form.cleaned_data['with_entity_subordinated'] if value: entity_ids = get_entities_ids(value, with_subordinated) queryset = queryset.filter( learning_container_year__requirement_entity__in=entity_ids) return queryset def filter_allocation_entity_with_entity_subordinated( self, queryset, name, value): with_subordinated = self.form.cleaned_data['with_entity_subordinated'] if value: entity_ids = get_entities_ids(value, with_subordinated) queryset = queryset.filter( learning_container_year__allocation_entity__in=entity_ids) return queryset @property def qs(self): queryset = super(LearningUnitDescriptionFicheFilter, self).qs if self.is_bound: queryset = self._compute_summary_status(queryset) queryset = queryset.select_related( 'learning_container_year__academic_year', 'academic_year') return queryset def _compute_summary_status(self, queryset): """ This function will compute the summary status. First, we will take the entity calendar (or entity calendar parent and so one) of the requirement entity. If not found, the summary status is computed with the general Academic Calendar Object """ entity_calendars_computed = entity_calendar.build_calendar_by_entities( self.form.cleaned_data['academic_year'].past(), SUMMARY_COURSE_SUBMISSION, ) requirement_entities_ids = queryset.values_list( 'learning_container_year__requirement_entity', flat=True) summary_status_case_statment = [ When(last_translated_text_changed__isnull=True, then=False) ] for requirement_entity_id in set(requirement_entities_ids): start_summary_course_submission = entity_calendars_computed.get( requirement_entity_id, {}).get('start_date') if start_summary_course_submission is None: continue summary_status_case_statment.append( When(learning_container_year__requirement_entity= requirement_entity_id, last_translated_text_changed__gte= start_summary_course_submission, then=True)) queryset = queryset.annotate( summary_status=Case(*summary_status_case_statment, default=Value(False), output_field=BooleanField())) return queryset
class CollectionVersionFilter(ContentFilter): """ FilterSet for Ansible CollectionVersions. """ namespace = filters.CharFilter(field_name="namespace") name = filters.CharFilter(field_name="name") is_highest = filters.BooleanFilter(field_name="is_highest", method="get_highest") certification = MultipleChoiceFilter(choices=CollectionVersion.CERTIFICATION_CHOICES) deprecated = filters.BooleanFilter(field_name="collection__deprecated") q = filters.CharFilter(field_name="q", method="filter_by_q") tags = filters.CharFilter( field_name="tags", method="filter_by_tags", help_text=_("Filter by comma separate list of tags that must all be matched"), ) def filter_by_q(self, queryset, name, value): """ Full text search provided by the 'q' option. Args: queryset: The query to add the additional full-text search filtering onto name: The name of the option specified, i.e. 'q' value: The string to search on Returns: The Django queryset that was passed in, additionally filtered by full-text search. """ search_query = SearchQuery(value) qs = queryset.filter(search_vector=search_query) ts_rank_fn = Func( F("search_vector"), search_query, 32, # RANK_NORMALIZATION = 32 function="ts_rank", output_field=db_fields.FloatField(), ) return qs.annotate(rank=ts_rank_fn).order_by("-rank") def filter_by_tags(self, qs, name, value): """ Filter queryset qs by list of tags. Args: qs (django.db.models.query.QuerySet): CollectionVersion queryset value (string): A comma separated list of tags Returns: Queryset of CollectionVersion that matches all tags """ for tag in value.split(","): qs = qs.filter(tags__name=tag) return qs def get_highest(self, qs, name, value): """ Combine certification and is_highest filters. If certification and is_highest are used together, get the highest version for the specified certification """ certification = self.data.get("certification") if not certification: return qs.filter(is_highest=value) qs = qs.filter(certification=certification) if not qs.count(): return qs latest_pks = [] namespace_name_dict = defaultdict(lambda: defaultdict(list)) for collection in qs.all(): version_entry = (parse(collection.version), collection.pk) namespace_name_dict[collection.namespace][collection.name].append(version_entry) for namespace, name_dict in namespace_name_dict.items(): for name, version_list in name_dict.items(): version_list.sort(reverse=True) latest_pk = version_list[0][1] latest_pks.append(latest_pk) return qs.filter(pk__in=latest_pks) class Meta: model = CollectionVersion fields = ["namespace", "name", "version", "q", "is_highest", "certification", "tags"]
class EducationGroupFilter(FilterSet): academic_year = filters.ModelChoiceFilter( queryset=AcademicYear.objects.all(), required=False, empty_label=pgettext_lazy("plural", "All"), label=_('Ac yr.')) category = filters.ChoiceFilter( choices=list(Categories.choices()), required=False, label=_('Category'), field_name='education_group_type__category', empty_label=pgettext_lazy("plural", "All")) education_group_type = filters.ModelChoiceFilter( queryset=EducationGroupType.objects.none(), required=False, empty_label=pgettext_lazy("plural", "All"), label=_('Type'), widget=SelectWithData) management_entity = filters.CharFilter( method='filter_with_entity_subordinated', label=_('Entity')) with_entity_subordinated = filters.BooleanFilter( method=lambda queryset, *args, **kwargs: queryset, label=_('With subord. ent.'), widget=forms.CheckboxInput) acronym = filters.CharFilter( field_name="acronym", lookup_expr='icontains', max_length=40, required=False, label=_('Acronym/Short title'), ) title = filters.CharFilter(field_name="title", lookup_expr='icontains', max_length=255, required=False, label=_('Title')) partial_acronym = filters.CharFilter( field_name="partial_acronym", lookup_expr='icontains', max_length=15, required=False, label=_('Code'), ) order_by_field = 'ordering' ordering = OrderingFilter( fields=(('acronym', 'acronym'), ('partial_acronym', 'code'), ('academic_year__year', 'academic_year'), ('title', 'title'), ('education_group_type__name', 'type'), ('management_entity__entityversion__acronym', 'management_entity')), widget=forms.HiddenInput) class Meta: model = EducationGroupYear fields = [ 'acronym', 'partial_acronym', 'title', 'education_group_type__name', 'management_entity', 'with_entity_subordinated', ] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.form.fields[ 'education_group_type'].queryset = EducationGroupType.objects.all( ).order_by_translated_name() self.form.fields['academic_year'].initial = current_academic_year() self.form.fields[ 'category'].initial = education_group_categories.TRAINING def filter_with_entity_subordinated(self, queryset, name, value): with_subordinated = self.form.cleaned_data['with_entity_subordinated'] if value: entity_ids = get_entities_ids(value, with_subordinated) queryset = queryset.filter(management_entity__in=entity_ids) return queryset
class LineFilter(EDDObjectFilter): contact = django_filters.ModelChoiceFilter( field_name="contact", help_text=_("ID of the user set as the Line contact"), queryset=User.objects.all(), ) control = django_filters.BooleanFilter( field_name="control", help_text=_( "Filter on Lines marked as controls (True/1/yes or false/0/no)"), ) experimenter = django_filters.ModelChoiceFilter( field_name="experimenter", help_text=_("ID of the user set as the Line experimenter"), queryset=User.objects.all(), ) in_study = django_filters.CharFilter( field_name="study", help_text=_("An identifier for the study; can use ID, UUID, or Slug"), method=filter_in_study, ) replicates = django_filters.CharFilter( help_text=_("Flag to organize Lines by grouping together replicates"), method="group_replicates", ) strain = django_filters.CharFilter( field_name="strains", help_text=_( "Search on a strain UUID or registry URLs, separated by commas"), method="filter_strains", ) study = django_filters.ModelChoiceFilter( field_name="study", help_text=_("ID of the study the Line(s) are linked to"), queryset=models.Study.objects.all(), ) class Meta: model = models.Line fields = [] def filter_strains(self, queryset, name, values): # split out multiple values similar to other django_filters 'in' param processing uuid_values, url_values = [], [] for value in values.split(","): try: uuid_values.append(UUID(value)) except ValueError: url_values.append(value) match_uuid = Q(strains__registry_id__in=uuid_values) match_url = Q(strains__registry_url__in=url_values) return queryset.filter(match_uuid | match_url) def group_replicates(self, queryset, name, value): if self.truthy(value): replicate_type = models.MetadataType.system("Replicate") # extract replicate key from metadata replicate = Func( F("metadata"), Value(f"{replicate_type.id}"), function="jsonb_extract_path_text", output_field=CharField(), ) # define fallback of line's UUID when no metadata replicate value replicate_key = Coalesce(replicate, Cast("uuid", output_field=CharField())) return queryset.annotate(replicate_key=replicate_key) return queryset
class MeasurementFilter(filters.FilterSet): active = django_filters.BooleanFilter( field_name="active", help_text= _("Filter on currently active/visible items (True/1/yes or false/0/no)" ), ) assay = ModelChoiceInFilter( field_name="assay", help_text=_("IDs of assay(s) to limit measurements"), queryset=models.Assay.objects.all(), ) created_before = django_filters.IsoDateTimeFilter( field_name="created__mod_time", help_text=_("Use an ISO-8601-like datetime: 2020-01-01 00:00:00"), lookup_expr="lte", ) created_after = django_filters.IsoDateTimeFilter( field_name="created__mod_time", help_text=_("Use an ISO-8601-like datetime: 2020-01-01 00:00:00"), lookup_expr="gte", ) compartment = django_filters.ChoiceFilter( choices=models.Measurement.Compartment.CHOICE, field_name="compartment", help_text= _("One of the compartment codes, 0, 1, 2 for N/A, Intracellular, Extracellular" ), ) format = django_filters.ChoiceFilter( choices=models.Measurement.Format.CHOICE, field_name="measurement_format", help_text=_("One of the format codes; currently only '0' for Scalar " "format values is supported"), ) in_study = django_filters.CharFilter( field_name="study", help_text=_("An identifier for the study; can use ID, UUID, or Slug"), method=filter_in_study, ) line = ModelChoiceInFilter( field_name="assay__line", help_text=_("IDs of line(s) to limit measurements"), queryset=models.Line.objects.all(), ) protocol = ModelChoiceInFilter( field_name="assay__protocol", help_text=_("IDs of protocol(s) to limit measurements"), queryset=models.Protocol.objects.all(), ) type = ModelChoiceInFilter( field_name="measurement_type", help_text=_("IDs of measurement type(s) to limit measurements"), queryset=models.MeasurementType.objects.all(), ) x_units = ModelChoiceInFilter( field_name="x_units", help_text=_("IDs of unit(s) used on the x-axis to limit measurements"), queryset=models.MeasurementUnit.objects.all(), ) y_units = ModelChoiceInFilter( field_name="y_units", help_text=_("IDs of unit(s) used on the y-axis to limit measurements"), queryset=models.MeasurementUnit.objects.all(), ) class Meta: model = models.Measurement fields = []
class DepartmentFilterSet(FilterSet): is_intern = filters.BooleanFilter() order_by = OrderingFilter(fields=(('code', 'code')))
class FeatureFilter(GeoFilterSet): """Filter Feature model objects.""" geometry = GeometryFilter( name='geometry', lookup_expr='intersects', help_text="""Geospatial filter of features whose geometry intersects with another geometry. You can use any geometry type in this filter.""") checked = filters.BooleanFilter( widget=BooleanWidget(), help_text="""Filter features that were checked or not. Use true/false or 1/0 values.""") changeset_checked = filters.BooleanFilter( name='changeset__checked', widget=BooleanWidget(), help_text="""Filter features whose changeset is checked or not. Use true/false or 1/0 values.""") harmful = filters.BooleanFilter( widget=BooleanWidget(), help_text="""Filter features that were marked as harmful or not harmful. Use true/false or 1/0 values.""") users = filters.CharFilter( name='changeset__user', method='filter_changeset_users', help_text="""Filter features whose last edit was made by a user. Use commas to search for more than one username.""") uids = filters.CharFilter( name='changeset__uid', method='filter_changeset_uid', help_text="""Filter features whose last edit was made by a user. Use commas to search for more than one user uid. The uid is a unique identifier of a OSM user.""") checked_by = filters.CharFilter( name='check_user', method='filter_check_users', help_text="""Filter features that were checked by a user. Use commas to search for more than one user.""") order_by = filters.CharFilter( name=None, method='order_queryset', help_text="""Order the Features by one of the following fields: id, osm_id, changeset__date, changeset_id, check_date or number_reasons. Use a minus sign (-) before the field name to reverse the ordering. Default ordering is '-changeset_id'.""") changeset_ids = filters.CharFilter( name='changeset__id', method='filter_changeset_ids', help_text="""Filter features by its changeset id. Send the ids separated by commas.""") osm_version__gte = filters.NumberFilter( name='osm_version', lookup_expr='gte', help_text="""Filter items whose osm_version is greater than or equal to a number.""") osm_version__lte = filters.NumberFilter( name='osm_version', lookup_expr='lte', help_text="""Filter items whose osm_version is lower than or equal to a number.""") osm_type = filters.CharFilter( name='osm_type', lookup_expr='exact', help_text="""Filter features by its osm_type. The value options are node, way or relation.""") date__gte = filters.DateTimeFilter( name='changeset__date', lookup_expr='gte', help_text="""Filter features whose changeset date is greater than or equal to a date or a datetime.""") date__lte = filters.DateTimeFilter( name='changeset__date', lookup_expr='lte', help_text="""Filter features whose changeset date is lower than or equal to a date or a datetime.""") check_date__gte = filters.DateTimeFilter( name='check_date', lookup_expr='gte', help_text="""Filter features whose check_date is greater than or equal to a date or a datetime.""") check_date__lte = filters.DateTimeFilter( name='check_date', lookup_expr='lte', help_text="""Filter features whose check_date is lower than or equal to a date or a datetime.""") editor = filters.CharFilter( name='changeset__editor', lookup_expr='icontains', help_text="""Filter features that were created or last modified with a software editor. The lookup expression used is 'icontains', so a query for 'josm' will get features created or last modified with all JOSM versions. """) reasons = filters.CharFilter( name='reasons', method='filter_any_reasons', help_text="""Filter features that have one or more of the Suspicion Reasons. Inform the Suspicion Reasons ids separated by commas.""") all_reasons = filters.CharFilter( name='reasons', method='filter_all_reasons', help_text="""Filter features that have ALL the Suspicion Reasons of a list. Inform the Suspicion Reasons ids separated by commas.""") number_reasons__gte = filters.NumberFilter( name='number_reasons', method='filter_number_reasons', help_text="""Filter features whose number of Suspicion Reasons is equal or greater than a value.""") tags = filters.CharFilter( name='tags', method='filter_any_reasons', help_text="""Filter features that have one or more of the Tags. Inform the Tags ids separated by commas.""") all_tags = filters.CharFilter( name='tags', method='filter_all_reasons', help_text="""Filter features that have ALL the Tags of a list. Inform the Tags ids separated by commas.""") def filter_changeset_users(self, queryset, name, value): if (self.request is None or self.request.user.is_authenticated) and value: lookup = '__'.join([name, 'in']) users_array = [t.strip() for t in value.split(',')] return queryset.filter(**{lookup: users_array}) else: return queryset def filter_changeset_uid(self, queryset, name, value): if (self.request is None or self.request.user.is_authenticated) and value: lookup = '__'.join([name, 'in']) uids_array = [t.strip() for t in value.split(',')] return queryset.filter(**{lookup: uids_array}) else: return queryset def filter_check_users(self, queryset, name, value): if (self.request is None or self.request.user.is_authenticated) and value: lookup = '__'.join([name, 'name', 'in']) check_users_array = [t.strip() for t in value.split(',')] return queryset.filter(**{lookup: check_users_array}) else: return queryset def filter_any_reasons(self, queryset, name, value): lookup = '__'.join([name, 'id', 'in']) values = [int(t) for t in value.split(',')] return queryset.filter(**{lookup: values}).distinct() def filter_all_reasons(self, queryset, name, value): lookup = '__'.join([name, 'id']) values = [int(t) for t in value.split(',')] for term in values: queryset = queryset.filter(**{lookup: term}) return queryset def filter_number_reasons(self, queryset, name, value): lookup = '__'.join([name, 'gte']) queryset = queryset.annotate(number_reasons=Count('reasons')) return queryset.filter(**{lookup: value}) def order_queryset(self, queryset, name, value): allowed_fields = [ '-id', 'id', '-osm_id', 'osm_id', 'changeset__date', '-changeset__date', 'changeset_id', 'check_date', '-check_date', 'number_reasons', '-number_reasons' ] if value in allowed_fields: if value in ['number_reasons', '-number_reasons']: queryset = queryset.annotate(number_reasons=Count('reasons')) return queryset.order_by(value) else: return queryset def filter_changeset_ids(self, queryset, name, value): lookup = '__'.join([name, 'in']) values = [int(t) for t in value.split(',')] return queryset.filter(**{lookup: values}) class Meta: model = Feature fields = []
class EducationGroupFilter(FilterSet): academic_year = filters.ModelChoiceFilter( queryset=AcademicYear.objects.all(), required=False, label=_('Ac yr.'), empty_label=pgettext_lazy("plural", "All"), ) category = filters.ChoiceFilter( choices=list(Categories.choices()), required=False, label=_('Category'), field_name='education_group_type__category', empty_label=pgettext_lazy("plural", "All")) education_group_type = filters.ModelMultipleChoiceFilter( queryset=EducationGroupType.objects.none(), required=False, label=_('Type'), widget=autocomplete.ModelSelect2Multiple( url='education_group_type_autocomplete', forward=['category'], ), ) management_entity = filters.CharFilter( method='filter_with_entity_subordinated', label=_('Entity')) with_entity_subordinated = filters.BooleanFilter( method=lambda queryset, *args, **kwargs: queryset, label=_('Include subordinate entities'), widget=forms.CheckboxInput) acronym = filters.CharFilter( field_name="acronym", method="filter_education_group_year_field", max_length=40, required=False, label=_('Acronym/Short title'), ) title = filters.CharFilter(field_name="title", method='filter_education_group_year_field', max_length=255, required=False, label=_('Title')) partial_acronym = filters.CharFilter( field_name="partial_acronym", method='filter_education_group_year_field', max_length=15, required=False, label=_('Code'), ) order_by_field = 'ordering' ordering = OrderingFilter( fields=(('acronym', 'acronym'), ('partial_acronym', 'code'), ('academic_year__year', 'academic_year'), ('title', 'title'), ('type_ordering', 'type'), ('entity_management_version', 'management_entity')), widget=forms.HiddenInput) class Meta: model = EducationGroupYear fields = [ 'acronym', 'partial_acronym', 'title', 'education_group_type__name', 'management_entity', 'with_entity_subordinated', ] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.queryset = self.get_queryset() self.form.fields[ 'education_group_type'].queryset = EducationGroupType.objects.all( ).order_by_translated_name() self.form.fields['academic_year'].initial = starting_academic_year() self.form.fields[ 'category'].initial = education_group_categories.TRAINING self.form.fields["with_entity_subordinated"].initial = kwargs.pop( 'with_entity_subordinated', True) def filter_with_entity_subordinated(self, queryset, name, value): with_subordinated = self.form.cleaned_data['with_entity_subordinated'] if value: entity_ids = get_entities_ids(value, with_subordinated) queryset = queryset.filter(management_entity__in=entity_ids) return queryset @staticmethod def filter_education_group_year_field(queryset, name, value): return filter_field_by_regex(queryset, name, value) def get_queryset(self): # Need this close so as to return empty query by default when form is unbound if not self.data: return EducationGroupYear.objects.none() management_entity = entity_version.EntityVersion.objects.filter( entity=OuterRef('management_entity'), ).current( OuterRef('academic_year__start_date')).values('acronym')[:1] return EducationGroupYear.objects.all().annotate(type_ordering=Case( *[ When(education_group_type__name=key, then=Value(str(_(val)))) for i, (key, val) in enumerate(education_group_types.ALL_TYPES) ], default=Value(''), output_field=CharField())).annotate( entity_management_version=Subquery(management_entity)) def filter_queryset(self, queryset): # Order by id to always ensure same order when objects have same values for order field (ex: title) qs = super().filter_queryset(queryset) order_fields = qs.query.order_by + ('id', ) return qs.order_by(*order_fields)
class CustomerInfoFilter(FilterSet): corporate_number = filters.CharFilter( name='corporate_number', label='法人番号', lookup_expr='contains') optional_code1 = filters.CharFilter( name='optional_code1', label='任意コード1', lookup_expr='contains') optional_code2 = filters.CharFilter( name='optional_code2', label='任意コード2', lookup_expr='contains') optional_code3 = filters.CharFilter( name='optional_code3', label='任意コード3', lookup_expr='contains') customer_name = filters.CharFilter( name='customer_name', label='企業名', lookup_expr='contains') department_name = filters.CharFilter( name='department_name', label='部署名', lookup_expr='contains') tel_number1 = filters.CharFilter( name='tel_number1', label='電話番号1', lookup_expr='contains') tel_number2 = filters.CharFilter( name='tel_number2', label='電話番号2', lookup_expr='contains') tel_number3 = filters.CharFilter( name='tel_number3', label='電話番号3', lookup_expr='contains') fax_number = filters.CharFilter( name='fax_number', label='FAX番号', lookup_expr='contains') mail_address = filters.CharFilter( name='mail_address', label='メールアドレス', lookup_expr='contains') representative = filters.CharFilter( name='representative', label='代表者名', lookup_expr='contains') contact_name = filters.CharFilter( name='contact_name', label='担当者名', lookup_expr='contains') zip_code = filters.CharFilter( name='zip_code', label='郵便番号', lookup_expr='contains') address1 = filters.CharFilter( name='address1', label='都道府県', lookup_expr='contains') address2 = filters.CharFilter( name='address2', label='市区町村番地', lookup_expr='contains') address3 = filters.CharFilter( name='address3', label='建物名', lookup_expr='contains') latitude_gte = filters.CharFilter( name='latitude', label='緯度(以上)', lookup_expr='gte') latitude_lte = filters.CharFilter( name='latitude', label='緯度(以下)', lookup_expr='lte') longitude_gte = filters.CharFilter( name='longitude', label='経度(以上)', lookup_expr='gte') longitude_lte = filters.CharFilter( name='longitude', label='経度(以下)', lookup_expr='lte') url1 = filters.CharFilter( name='url1', label='企業URL1', lookup_expr='contains') url2 = filters.CharFilter( name='url2', label='企業URL2', lookup_expr='contains') url3 = filters.CharFilter( name='url3', label='企業URL3', lookup_expr='contains') industry_code = filters.CharFilter( name='industry_code', label='業種', lookup_expr='contains') contracted_flg = filters.BooleanFilter(name='contracted_flg', label='契約済み') data_source = filters.CharFilter( name='data_source', label='データソース', lookup_expr='contains') potential_gte = filters.CharFilter( name='potential', label='ポテンシャル(以上)', lookup_expr='gte') potential_lte = filters.CharFilter( name='potential', label='ポテンシャル(以下)', lookup_expr='lte') remarks = filters.CharFilter( name='remarks', label='備考', lookup_expr='contains') author = filters.CharFilter( name='author', label='作成者', lookup_expr='contains') created_timestamp_gte = filters.CharFilter( name='created_timestamp', label='作成日時(以降)', lookup_expr='gte', widget=forms.TextInput(attrs={'placeholder': 'YYYY-MM-DD'})) created_timestamp_lte = filters.CharFilter( name='created_timestamp', label='作成日時(以前)', lookup_expr='lte', widget=forms.TextInput(attrs={'placeholder': 'YYYY-MM-DD'})) modifier = filters.CharFilter( name='modifier', label='修正者', lookup_expr='contains') modified_timestamp = filters.CharFilter( name='modified_timestamp', label='修正日時', lookup_expr='contains') action_status_ex = filters.CharFilter( name='action_status', label='除外する進捗状況', lookup_expr='exact', exclude=True) order_by = MyOrderingFilter( # tuple-mapping retains order fields=( ('customer_name', 'customer_name'), ('zip_code', 'zip_code'), ), field_labels={ 'customer_name': '企業名', 'zip_code': '郵便番号', }, label='並び順') class Meta: model = CustomerInfo fields = ( 'corporate_number', 'optional_code1', 'optional_code2', 'optional_code3', 'customer_name', 'department_name', 'tel_number1', 'tel_number2', 'tel_number3', 'fax_number', 'mail_address', 'representative', 'contact_name', 'zip_code', 'address1', 'address2', 'address3', 'url1', 'url2', 'url3', 'industry_code', 'data_source', 'contracted_flg', 'potential_gte', 'potential_lte', 'tel_limit_flg', 'fax_limit_flg', 'mail_limit_flg', 'attention_flg', 'remarks', 'sales_person', 'action_status', 'tel_called_flg', 'mail_sent_flg', 'fax_sent_flg', 'dm_sent_flg', 'visited_flg', 'public_status', 'author', 'created_timestamp_gte', 'created_timestamp_lte', 'latitude_gte', 'latitude_lte', 'longitude_gte', 'longitude_lte', 'modifier', 'modified_timestamp', )
class CollectionByCollectionVersionFilter(pulp_ansible_viewsets.CollectionVersionFilter): """pulp_ansible CollectionVersion filter for Collection viewset.""" versioning_class = versioning.UIVersioning keywords = filters.CharFilter(field_name="keywords", method="filter_by_q") deprecated = filters.BooleanFilter()
class ChangesetFilter(GeoFilterSet): """Allows to filter Changesets by any of its fields, except 'uuid' (id of OSM user). The 'reasons' and the 'harmful_reasons' fields can be filtered by the exact match (filter changesets that have all the search reasons) or by contains match (filter changesets that have any of the reasons). """ geometry = GeometryFilter( field_name='bbox', lookup_expr='intersects', help_text="""Geospatial filter of changeset whose bbox intersects with another geometry. You can use any geometry type in this filter.""") checked_by = filters.CharFilter( field_name='check_user', method='filter_checked_by', help_text="""Filter changesets that were checked by a user. Use commas to search for more than one user.""") users = filters.CharFilter( field_name='user', method='filter_users', help_text="""Filter changesets created by a user. Use commas to search for more than one user.""") ids = filters.CharFilter( field_name='id', method='filter_ids', help_text="""Filter changesets by its ID. Use commas to search for more than one id.""") uids = filters.CharFilter( field_name='uid', method='filter_uids', help_text="""Filter changesets by its uid. The uid is a unique identifier of each user in OSM. Use commas to search for more than one uid.""") checked = filters.BooleanFilter( field_name='checked', widget=BooleanWidget(), help_text="""Filter changesets that were checked or not. Use true/false, 1/0 values.""") harmful = filters.BooleanFilter( field_name='harmful', widget=BooleanWidget(), help_text="""Filter changesets that were marked as harmful or not. Use true/false, 1/0 values.""") is_suspect = filters.BooleanFilter( field_name='is_suspect', widget=BooleanWidget(), help_text='Filter changesets that were considered suspect by OSMCHA.') powerfull_editor = filters.BooleanFilter( field_name='powerfull_editor', widget=BooleanWidget(), help_text="""Filter changesets that were created using a software editor considered powerfull (those that allow to create, modify or delete data in a batch).""") order_by = filters.CharFilter( field_name='order', method='order_queryset', help_text="""Order the Changesets by one of the following fields: id, date, check_date, create, modify, delete or number_reasons. Use a minus sign (-) before the field name to reverse the ordering. Default ordering is '-id'.""") hide_whitelist = filters.BooleanFilter( field_name='user', method='filter_whitelist', widget=BooleanWidget(), help_text="""If True, it will exclude the changesets created by the users that you whitelisted.""") blacklist = filters.BooleanFilter( field_name='user', method='filter_blacklist', widget=BooleanWidget(), help_text="""If True, it will get only the changesets created by the users that you blacklisted.""") mapping_teams = filters.CharFilter( field_name='user', method='filter_mapping_team', help_text="""Filter changesets created by users that are on a Mapping Team. It accepts a list of teams separated by commas.""") exclude_teams = filters.CharFilter( field_name='user', method='exclude_mapping_team', help_text="""Exclude changesets created by users that are on a Mapping Team. It accepts a list of teams separated by commas.""") exclude_trusted_teams = filters.BooleanFilter( field_name='user', method='filter_hide_trusted_teams', widget=BooleanWidget(), help_text="""If True, it will exclude the changesets created by the users that are part of trusted teams.""") area_lt = filters.CharFilter( field_name='user', method='filter_area_lt', help_text="""Filter changesets that have a bbox area lower than X times the area of your geospatial filter. For example, if the bbox or geometry you defined in your filter has an area of 1 degree and you set 'area_lt=2', it will filter the changesets whose bbox area is lower than 2 degrees.""") create__gte = filters.NumberFilter( field_name='create', lookup_expr='gte', help_text="""Filter changesets whose number of elements created are greater than or equal to a number.""") create__lte = filters.NumberFilter( field_name='create', lookup_expr='lte', help_text="""Filter changesets whose number of elements created are lower than or equal to a number.""") modify__gte = filters.NumberFilter( field_name='modify', lookup_expr='gte', help_text="""Filter changesets whose number of elements modified are greater than or equal to a number.""") modify__lte = filters.NumberFilter( field_name='modify', lookup_expr='lte', help_text="""Filter changesets whose number of elements modified are lower than or equal to a number.""") delete__gte = filters.NumberFilter( field_name='delete', lookup_expr='gte', help_text="""Filter changesets whose number of elements deleted are greater than or equal to a number.""") delete__lte = filters.NumberFilter( field_name='delete', lookup_expr='lte', help_text="""Filter changesets whose number of elements deleted are lower than or equal to a number.""") date__gte = filters.DateTimeFilter( field_name='date', lookup_expr='gte', help_text="""Filter changesets whose date is greater than or equal to a date or a datetime value.""") date__lte = filters.DateTimeFilter( field_name='date', lookup_expr='lte', help_text="""Filter changesets whose date is lower than or equal to a date or a datetime value.""") check_date__gte = filters.DateTimeFilter( field_name='check_date', lookup_expr='gte', help_text="""Filter changesets whose check_date is greater than or equal to a date or a datetime value.""") check_date__lte = filters.DateTimeFilter( field_name='check_date', lookup_expr='lte', help_text="""Filter changesets whose check_date is lower than or equal to a date or a datetime value.""") editor = filters.CharFilter( field_name='editor', lookup_expr='icontains', help_text="""Filter changesets created with a software editor. It uses the icontains lookup expression, so a query for 'josm' will return changesets created or last modified with all JOSM versions.""") comment = filters.CharFilter( field_name='comment', lookup_expr='icontains', help_text="""Filter changesets by its comment field using the icontains lookup expression.""") source = filters.CharFilter( field_name='source', lookup_expr='icontains', help_text="""Filter changesets by its source field using the icontains lookup expression.""") imagery_used = filters.CharFilter( field_name='imagery_used', lookup_expr='icontains', help_text="""Filter changesets by its imagery_used field using the icontains lookup expression.""") reasons = filters.CharFilter( field_name='reasons', method='filter_any_reasons', help_text="""Filter changesets that have one or more of the Suspicion Reasons. Inform the Suspicion Reasons ids separated by commas.""") all_reasons = filters.CharFilter( field_name='reasons', method='filter_all_reasons', help_text="""Filter changesets that have ALL the Suspicion Reasons of a list. Inform the Suspicion Reasons ids separated by commas.""") number_reasons__gte = filters.NumberFilter( field_name='number_reasons', method='filter_number_reasons', help_text="""Filter changesets whose number of Suspicion Reasons is equal or greater than a value.""") tags = filters.CharFilter( field_name='tags', method='filter_any_reasons', help_text="""Filter changesets that have one or more of the Tags. Inform the Tags ids separated by commas.""") all_tags = filters.CharFilter( field_name='tags', method='filter_all_reasons', help_text="""Filter changesets that have ALL the Tags of a list. Inform the Tags ids separated by commas.""") def filter_whitelist(self, queryset, name, value): if (self.request is None or self.request.user.is_authenticated) and value: whitelist = self.request.user.whitelists.values_list( 'whitelist_user', flat=True) return queryset.exclude(user__in=whitelist) else: return queryset def filter_blacklist(self, queryset, name, value): if (self.request is None or self.request.user.is_authenticated) and value: blacklist = self.request.user.blacklisteduser_set.values_list( 'uid', flat=True) return queryset.filter(uid__in=blacklist) else: return queryset def get_username_from_teams(self, teams): users = [] for i in teams.values_list('users', flat=True): values = i if type(values) in [str, bytes, bytearray]: values = json.loads(values) for e in values: users.append(e.get('username')) return users def filter_mapping_team(self, queryset, name, value): try: # added `if team` to avoid empty strings teams = MappingTeam.objects.filter( name__in=[team.strip() for team in value.split(',') if team]) users = self.get_username_from_teams(teams) return queryset.filter(user__in=users) except MappingTeam.DoesNotExist: return queryset def exclude_mapping_team(self, queryset, name, value): try: teams = MappingTeam.objects.filter( name__in=[team.strip() for team in value.split(',') if team]) users = self.get_username_from_teams(teams) return queryset.exclude(user__in=users) except MappingTeam.DoesNotExist: return queryset def filter_hide_trusted_teams(self, queryset, name, value): teams = MappingTeam.objects.filter(trusted=True) users = self.get_username_from_teams(teams) if users: return queryset.exclude(user__in=users) else: return queryset def filter_checked_by(self, queryset, name, value): if (self.request is None or self.request.user.is_authenticated) and value: lookup = '__'.join([name, 'name__in']) users = [t.strip() for t in value.split(',')] return queryset.filter(**{lookup: users}) else: return queryset def filter_users(self, queryset, name, value): if (self.request is None or self.request.user.is_authenticated) and value: lookup = '__'.join([name, 'in']) users_array = [t.strip() for t in value.split(',')] return queryset.filter(**{lookup: users_array}) else: return queryset def filter_ids(self, queryset, name, value): lookup = '__'.join([name, 'in']) values = [int(n) for n in value.split(',')] return queryset.filter(**{lookup: values}) def filter_uids(self, queryset, name, value): if (self.request is None or self.request.user.is_authenticated) and value: lookup = '__'.join([name, 'in']) values = [n for n in value.split(',')] return queryset.filter(**{lookup: values}) else: return queryset def filter_any_reasons(self, queryset, name, value): lookup = '__'.join([name, 'id', 'in']) values = [int(t) for t in value.split(',')] return queryset.filter(**{lookup: values}).distinct() def filter_all_reasons(self, queryset, name, value): lookup = '__'.join([name, 'id']) values = [int(t) for t in value.split(',')] for term in values: queryset = queryset.filter(**{lookup: term}) return queryset def filter_number_reasons(self, queryset, name, value): lookup = '__'.join([name, 'gte']) queryset = queryset.annotate(number_reasons=Count('reasons')) return queryset.filter(**{lookup: value}) def order_queryset(self, queryset, name, value): allowed_fields = [ 'date', '-date', 'id', 'check_date', '-check_date', 'create', 'modify', 'delete', '-create', '-modify', '-delete', 'number_reasons', '-number_reasons' ] if value in allowed_fields: if value in ['number_reasons', '-number_reasons']: queryset = queryset.annotate(number_reasons=Count('reasons')) return queryset.order_by(value) else: return queryset def filter_area_lt(self, queryset, name, value): """This filter method was designed to exclude changesets that are much bigger than the filter area. For example, if you want to exclude changesets that are greater than 5 times the filter area, you need to set the value to 5. """ if 'geometry' in self.data.keys(): try: filter_area = self.data['geometry'].area except AttributeError: filter_area = GeometryField().to_internal_value( self.data['geometry']).area return queryset.filter(area__lt=float(value) * filter_area) elif 'in_bbox' in self.data.keys(): try: filter_area = Polygon.from_bbox( (float(n) for n in self.data['in_bbox'].split(','))).area return queryset.filter(area__lt=float(value) * filter_area) except ValueError: return queryset else: return queryset class Meta: model = Changeset fields = ['geometry', 'users', 'area_lt']
class LearningUnitFilter(FilterSet): academic_year = filters.ModelChoiceFilter( queryset=AcademicYear.objects.all(), required=False, label=_('Ac yr.'), empty_label=pgettext_lazy("plural", "All"), ) acronym = filters.CharFilter( field_name="acronym", lookup_expr="iregex", max_length=40, required=False, label=_('Code'), ) requirement_entity = filters.CharFilter( method='filter_entity', max_length=20, label=_('Req. Entity'), ) allocation_entity = filters.CharFilter( method='filter_entity', max_length=20, label=_('Alloc. Entity'), ) with_entity_subordinated = filters.BooleanFilter( method=lambda queryset, *args, **kwargs: queryset, label=_('Include subordinate entities'), widget=forms.CheckboxInput, initial='True' ) tutor = filters.CharFilter( method="filter_tutor", max_length=40, label=_('Tutor'), ) quadrimester = filters.ChoiceFilter( choices=quadrimesters.LEARNING_UNIT_YEAR_QUADRIMESTERS, required=False, field_name="quadrimester", label=_('Quadri'), empty_label=pgettext_lazy("plural", "All"), ) container_type = filters.ChoiceFilter( choices=LearningContainerYearType.choices() + MOBILITY_CHOICE, required=False, field_name="learning_container_year__container_type", label=_('Type'), empty_label=pgettext_lazy("plural", "All"), method="filter_container_type" ) subtype = filters.ChoiceFilter( choices=learning_unit_year_subtypes.LEARNING_UNIT_YEAR_SUBTYPES, required=False, field_name="subtype", label=_('Subtype'), empty_label=pgettext_lazy("plural", "All") ) status = filters.ChoiceFilter( choices=active_status.ACTIVE_STATUS_LIST_FOR_FILTER, required=False, label=_('Status'), field_name="status", empty_label=pgettext_lazy("plural", "All") ) title = filters.CharFilter( field_name="full_title", method="filter_learning_unit_year_field", max_length=40, label=_('Title'), ) search_type = filters.CharFilter( field_name="acronym", method=lambda request, *args, **kwargs: request, widget=forms.HiddenInput, required=False, initial=SearchTypes.SIMPLE_SEARCH.value ) order_by_field = 'ordering' ordering = OrderingFilter( fields=( ('academic_year__year', 'academic_year'), ('acronym', 'acronym'), ('full_title', 'title'), ('learning_container_year__container_type', 'type'), ('subtype', 'subtype'), ('entity_requirement', 'requirement_entity'), ('entity_allocation', 'allocation_entity'), ('credits', 'credits'), ('status', 'status'), ('has_proposal', 'has_proposal'), ), widget=forms.HiddenInput ) class Meta: model = LearningUnitYear fields = [ "academic_year", "acronym", "title", "container_type", "subtype", "requirement_entity", "allocation_entity", "credits", "status", ] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.queryset = self.get_queryset() self.form.fields["academic_year"].initial = starting_academic_year() def filter_tutor(self, queryset, name, value): for tutor_name in value.split(): queryset = queryset.filter( Q(learningcomponentyear__attributionchargenew__attribution__tutor__person__first_name__iregex=tutor_name ) | Q(learningcomponentyear__attributionchargenew__attribution__tutor__person__last_name__iregex=tutor_name) ).distinct() return queryset def filter_container_type(self, queryset, name, value): if value == MOBILITY: return queryset.filter(externallearningunityear__mobility=True) elif value == learning_container_year_types.EXTERNAL: return queryset.filter(externallearningunityear__co_graduation=True) return queryset.filter(learning_container_year__container_type=value) def filter_entity(self, queryset, name, value): return filter_by_entities(name, queryset, value, self.form.cleaned_data['with_entity_subordinated']) def get_queryset(self): # Need this close so as to return empty query by default when form is unbound if not self.data: return LearningUnitYear.objects.none() has_proposal = ProposalLearningUnit.objects.filter( learning_unit_year=OuterRef('pk'), ) queryset = LearningUnitYear.objects_with_container.select_related( 'academic_year', 'learning_container_year__academic_year', 'language', 'proposallearningunit', 'externallearningunityear' ).order_by('academic_year__year', 'acronym').annotate( has_proposal=Exists(has_proposal), ) queryset = LearningUnitYearQuerySet.annotate_full_title_class_method(queryset) queryset = LearningUnitYearQuerySet.annotate_entities_allocation_and_requirement_acronym(queryset) return queryset def filter_learning_unit_year_field(self, queryset, name, value): return filter_field_by_regex(queryset, name, value)
class ProposalLearningUnitFilter(FilterSet): academic_year = filters.ModelChoiceFilter( queryset=AcademicYear.objects.all(), required=False, label=_('Ac yr.'), empty_label=pgettext_lazy("plural", "All"), ) acronym = filters.CharFilter( field_name="acronym", lookup_expr="iregex", max_length=40, required=False, label=_('Code'), ) requirement_entity = filters.CharFilter( method='filter_entity', max_length=20, label=_('Req. Entity'), ) with_entity_subordinated = filters.BooleanFilter( method=lambda queryset, *args, **kwargs: queryset, label=_('Include subordinate entities'), widget=forms.CheckboxInput, initial='True') tutor = filters.CharFilter( method="filter_tutor", max_length=40, label=_('Tutor'), ) entity_folder = filters.ChoiceFilter( field_name="proposallearningunit__entity_id", label=_('Folder entity'), required=False, empty_label=pgettext_lazy("plural", "All"), ) folder = filters.NumberFilter(field_name="proposallearningunit__folder_id", min_value=0, required=False, label=_('Folder num.'), widget=forms.TextInput()) proposal_type = filters.ChoiceFilter( field_name="proposallearningunit__type", label=_('Proposal type'), choices=_get_sorted_choices(ProposalType.choices()), required=False, empty_label=pgettext_lazy("plural", "All"), ) proposal_state = filters.ChoiceFilter( field_name="proposallearningunit__state", label=_('Proposal status'), choices=_get_sorted_choices(ProposalState.choices()), required=False, empty_label=pgettext_lazy("plural", "All"), ) search_type = filters.CharFilter( field_name="acronym", method=lambda request, *args, **kwargs: request, widget=forms.HiddenInput, required=False, initial=SearchTypes.PROPOSAL_SEARCH.value) order_by_field = 'ordering' ordering = ProposalLearningUnitOrderingFilter( fields=( ('academic_year__year', 'academic_year'), ('acronym', 'acronym'), ('full_title', 'title'), ('learning_container_year__container_type', 'type'), ('entity_requirement', 'requirement_entity'), ('proposallearningunit__type', 'proposal_type'), ('proposallearningunit__state', 'proposal_state'), ('proposallearningunit__folder_id', 'folder'), # Overrided by ProposalLearningUnitOrderingFilter ), widget=forms.HiddenInput) class Meta: model = LearningUnitYear fields = [ "academic_year", "acronym", "subtype", "requirement_entity", ] def __init__(self, *args, person=None, **kwargs): super().__init__(*args, **kwargs) self.person = person self.queryset = self.get_queryset self._get_entity_folder_id_linked_ordered_by_acronym(self.person) # Academic year default value = n+1 for proposals search -> use event having n+1 as first open academic year event_perm = event_perms.EventPermCreationOrEndDateProposalFacultyManager( ) self.form.fields[ "academic_year"].initial = event_perm.get_academic_years().first() def _get_entity_folder_id_linked_ordered_by_acronym(self, person): most_recent_acronym = EntityVersion.objects.filter(entity__id=OuterRef( 'id'), ).order_by("-start_date").values('acronym')[:1] entities = Entity.objects.filter( proposallearningunit__isnull=False).annotate( entity_acronym=Subquery( most_recent_acronym)).distinct().order_by("entity_acronym") self.form.fields['entity_folder'].choices = [ (ent.pk, ent.entity_acronym) for ent in entities ] def filter_entity(self, queryset, name, value): with_subordinated = self.form.cleaned_data['with_entity_subordinated'] lookup_expression = "__".join(["learning_container_year", name, "in"]) if value: entity_ids = get_entities_ids(value, with_subordinated) queryset = queryset.filter(**{lookup_expression: entity_ids}) return queryset def filter_tutor(self, queryset, name, value): for tutor_name in value.split(): filter_by_first_name = Q( learningcomponentyear__attributionchargenew__attribution__tutor__person__first_name__iregex =tutor_name) filter_by_last_name = Q( learningcomponentyear__attributionchargenew__attribution__tutor__person__last_name__iregex =tutor_name) queryset = queryset.filter(filter_by_first_name | filter_by_last_name).distinct() return queryset @property def get_queryset(self): # Need this close so as to return empty query by default when form is unbound if not self.data: return LearningUnitYear.objects.none() entity_folder = EntityVersion.objects.filter( entity=OuterRef('proposallearningunit__entity'), ).current( OuterRef('academic_year__start_date')).values('acronym')[:1] has_proposal = ProposalLearningUnit.objects.filter( learning_unit_year=OuterRef('pk'), ) queryset = LearningUnitYear.objects_with_container.filter( proposallearningunit__isnull=False).select_related( 'academic_year', 'learning_container_year__academic_year', 'language', 'externallearningunityear', 'campus', 'proposallearningunit', 'campus__organization', ).prefetch_related("learningcomponentyear_set", ).annotate( has_proposal=Exists(has_proposal), entity_folder=Subquery(entity_folder), ) queryset = LearningUnitYearQuerySet.annotate_full_title_class_method( queryset) queryset = LearningUnitYearQuerySet.annotate_entities_allocation_and_requirement_acronym( queryset) return queryset