class PatientFilterSet(filters.FilterSet): source = filters.ChoiceFilter(choices=PatientRegistration.SourceChoices) disease_status = CareChoiceFilter(choice_dict=DISEASE_STATUS_DICT) facility = filters.UUIDFilter(field_name="facility__external_id") phone_number = filters.CharFilter(field_name="phone_number") allow_transfer = filters.BooleanFilter(field_name="allow_transfer") name = filters.CharFilter(field_name="name", lookup_expr="icontains") ip_no = filters.CharFilter(field_name="last_consultation__ip_no", lookup_expr="icontains") gender = filters.NumberFilter(field_name="gender") age = filters.NumberFilter(field_name="age") age_min = filters.NumberFilter(field_name="age", lookup_expr="gt") age_max = filters.NumberFilter(field_name="age", lookup_expr="lt") category = filters.ChoiceFilter(field_name="last_consultation__category", choices=CATEGORY_CHOICES) created_date = filters.DateFromToRangeFilter(field_name="created_date") modified_date = filters.DateFromToRangeFilter(field_name="modified_date") srf_id = filters.CharFilter(field_name="srf_id") is_declared_positive = filters.BooleanFilter(field_name="is_declared_positive") # Location Based Filtering district = filters.NumberFilter(field_name="district__id") district_name = filters.CharFilter(field_name="district__name", lookup_expr="icontains") local_body = filters.NumberFilter(field_name="local_body__id") local_body_name = filters.CharFilter(field_name="local_body__name", lookup_expr="icontains") state = filters.NumberFilter(field_name="state__id") state_name = filters.CharFilter(field_name="state__name", lookup_expr="icontains") # Consultation Fields last_consultation_admission_date = filters.DateFromToRangeFilter(field_name="last_consultation__admission_date") last_consultation_discharge_date = filters.DateFromToRangeFilter(field_name="last_consultation__discharge_date") last_consultation_admitted_to = filters.NumberFilter(field_name="last_consultation__admitted_to") last_consultation_assigned_to = filters.NumberFilter(field_name="last_consultation__assigned_to")
class WeatherDetailFilterSet(rest_filters.FilterSet): """Custom filterset for WeatherDetail""" FREQUENCY_CHOICES = (('daily', 'Daily'), ('weekly', 'Weekly'), ('monthly', 'Monthly')) FORMAT_CHOICES = (('fahrenheit', 'Temperature in fahrenheit'), ('celsius', 'Temperature in celsius')) frequency = rest_filters.ChoiceFilter( method='filter_frequency', choices=FREQUENCY_CHOICES, help_text='daily/weekly/monthly. Default is daily' ) start_date = rest_filters.DateFilter(name='date', lookup_expr='gte', help_text='start date (e.g) 2017-06-24') end_date = rest_filters.DateFilter(name='date', lookup_expr='lte', help_text='end date (e.g) 2017-06-26') city = rest_filters.CharFilter(name='city', lookup_expr='exact', help_text='city name (e.g) BERKHOUT, NL') temp_format = rest_filters.ChoiceFilter( method='filter_temp_format', choices=FORMAT_CHOICES, help_text='fahrenheit/celsius. Default is fahrenheit' ) class Meta: model = models.WeatherDetail fields = ['city', 'start_date', 'end_date', 'frequency'] @staticmethod def filter_frequency(queryset, name, value): """Returns queryset filtering based on the period selected.""" return queryset @staticmethod def filter_temp_format(queryset, name, value): """Returns the queryset based on the format as fahrenheit or celsius""" return queryset
class PlanSearchFilter(filters.FilterSet): """ 登山計画検索フィルタ """ purpose_type = filters.ChoiceFilter(choices=Plan.PURPOSE_TYPE, lookup_expr='exact') prefecture = filters.ChoiceFilter(choices=Plan.PREFECTURE, lookup_expr='exact') mountain_first = filters.CharFilter(lookup_expr='contains') mountain_second = filters.CharFilter(lookup_expr='contains') mountain_third = filters.CharFilter(lookup_expr='contains') mountain_fourth = filters.CharFilter(lookup_expr='contains') mountain_fifth = filters.CharFilter(lookup_expr='contains') from_entering_date = filters.DateFilter(field_name='entering_date', lookup_expr='gte') to_entering_date = filters.DateFilter(field_name='entering_date', lookup_expr='lte') class Meta: model = Plan fields = [ 'purpose_type', 'prefecture', 'mountain_first', 'mountain_second', 'mountain_third', 'mountain_fourth', 'mountain_fifth', 'from_entering_date', 'to_entering_date' ]
class StorageMediumFilter(filters.FilterSet): status = ListFilter(field_name='status', distinct='true') medium_type = filters.ChoiceFilter(field_name='storage_target__type', choices=medium_type_CHOICES) storage_type = filters.ChoiceFilter( field_name= 'storage_target__storage_method_target_relations__storage_method__type', choices=storage_type_CHOICES) deactivatable = filters.BooleanFilter(label='deactivatable', method='filter_deactivatable') include_inactive_ips = filters.BooleanFilter( method='filter_include_inactive_ips') migratable = filters.BooleanFilter(label='migratable', method='filter_migratable') medium_id_range = CharSuffixRangeFilter(field_name='medium_id') policy = filters.ModelChoiceFilter( label='Policy', queryset=StoragePolicy.objects.all(), field_name= 'storage_target__storage_method_target_relations__storage_method__storage_policies', distinct=True) def filter_include_inactive_ips(self, queryset, *args): # this filter is only used together with deactivatable return queryset def filter_deactivatable(self, queryset, name, value): include_inactive_ips = self.request.query_params.get( 'include_inactive_ips', False) include_inactive_ips = include_inactive_ips in (True, 'True', 'true', '1') return queryset.deactivatable( include_inactive_ips=include_inactive_ips) def filter_migratable(self, queryset, name, value): if value: return queryset.migratable() else: return queryset.non_migratable() ordering = StorageMediumOrderingFilter(fields=( ('id', 'id'), ('medium_id', 'medium_id'), ('storage_target__name', 'storage_target'), ('storage_target__max_capacity', 'max_capacity'), ('status', 'status'), ('location', 'location'), ('location_status', 'location_status'), ('used_capacity', 'used_capacity'), ('create_date', 'create_date'), ), ) class Meta: model = StorageMedium fields = ( 'status', 'medium_type', 'storage_type', 'medium_id', )
class PatientSampleFilterSet(filters.FilterSet): district = filters.NumberFilter( field_name="consultation__facility__district_id") district_name = filters.CharFilter( field_name="consultation__facility__district__name", lookup_expr="icontains") status = filters.ChoiceFilter( choices=PatientSample.SAMPLE_TEST_FLOW_CHOICES) result = filters.ChoiceFilter( choices=PatientSample.SAMPLE_TEST_RESULT_CHOICES)
class PatientFilterSet(filters.FilterSet): source = filters.ChoiceFilter(choices=PatientRegistration.SourceChoices) disease_status = CareChoiceFilter(choice_dict=DISEASE_STATUS_DICT) facility = filters.UUIDFilter(field_name="facility__external_id") phone_number = filters.CharFilter(field_name="phone_number") allow_transfer = filters.BooleanFilter(field_name="allow_transfer") name = filters.CharFilter(field_name="name", lookup_expr="icontains") ip_no = filters.CharFilter(field_name="last_consultation__ip_no", lookup_expr="icontains") gender = filters.BooleanFilter(field_name="gender") age = filters.NumericRangeFilter(field_name="age") category = filters.ChoiceFilter(field_name="last_consultation__category", choices=CATEGORY_CHOICES)
class StorageMediumFilter(filters.FilterSet): status = ListFilter(field_name='status', distinct='true') medium_type = filters.ChoiceFilter(field_name='storage_target__type', choices=medium_type_CHOICES) storage_type = filters.ChoiceFilter( field_name= 'storage_target__storage_method_target_relations__storage_method__type', choices=storage_type_CHOICES) class Meta: model = StorageMedium fields = ('status', 'medium_type', 'storage_type')
class ConcernFilter(drf_filters.FilterSet): type = drf_filters.ChoiceFilter(choices=models.ConcernType.choices) cause = drf_filters.ChoiceFilter(choices=models.ConcernCause.choices) object_id = drf_filters.NumberFilter(label='Related object ID', method='_pass') object_type = drf_filters.ChoiceFilter(label='Related object type', choices=CHOICES, method='_filter_by_object') owner_type = drf_filters.ChoiceFilter(choices=CHOICES, method='_filter_by_owner_type') class Meta: model = models.ConcernItem fields = [ 'name', 'type', 'cause', 'object_type', 'object_id', 'owner_type', 'owner_id', ] def _filter_by_owner_type(self, queryset, name, value: str): owner_type = ContentType.objects.get(app_label='cm', model=OBJECT_TYPES[value]) return queryset.filter(owner_type=owner_type) def _pass(self, queryset, name, value): # do not pass to filter directly return queryset def _filter_by_object(self, queryset, name, value): object_id = self.request.query_params.get('object_id') filters = {f'{OBJECT_TYPES[value]}_entities__id': object_id} return queryset.filter(**filters) def is_valid(self): object_type = self.request.query_params.get('object_type') object_id = self.request.query_params.get('object_id') both_present = all((object_id, object_type)) none_present = not any((object_id, object_type)) if not (both_present or none_present): raise AdcmEx( 'BAD_QUERY_PARAMS', msg= 'Both object_type and object_id params are expected or none of them', ) return super().is_valid()
class ContactDetailsFilter(filters.FilterSet): id = filters.NumberFilter(name="id", label="ID", lookup_expr="exact") id_range = filters.RangeFilter(name="id", label="ID Between") sme = filters.CharFilter(name="sme__name__username", label="Sme name", lookup_expr="icontains") type = filters.ChoiceFilter(name="type", choices=(('primary', 'primary'), ('secondary', 'secondary')), label="Type") name = filters.CharFilter(name="name", label="Name", lookup_expr="icontains") name_null = filters.BooleanFilter(name="name", label="Is name null", lookup_expr="isnull") phone = filters.CharFilter(name="phone", label="Phone", lookup_expr="icontains") phone_null = filters.BooleanFilter(name="phone", label="Is Phone null", lookup_expr="isnull") email = filters.CharFilter(name="email", label="Email", lookup_expr="icontains") email_null = filters.BooleanFilter(name="email", label="Is Email null", lookup_expr="isnull") designation = filters.CharFilter(name="designation", label="Designation", lookup_expr="icontains") designation_null = filters.BooleanFilter(name="designation", label="Is Designation null", lookup_expr="isnull") status = filters.ChoiceFilter(name="status", choices=(('active', 'active'), ('inactive', 'inactive')), label="Type") created_on = filters.IsoDateTimeFilter(name="created_on", label="Created on") created_between = filters.DateTimeFromToRangeFilter( name="created_on", label="Created Between") class Meta: model = ContactDetails fields = []
class HarvestFilter(filters.FilterSet): seasons = [] for y in Harvest.objects.all(): if y.start_date is not None: t_seasons = (y.start_date.strftime("%Y"), y.start_date.strftime("%Y")) seasons.append(t_seasons) seasons = list(set(seasons)) seasons = sorted(seasons, key=lambda tup: tup[1]) start_date = filters.ChoiceFilter( choices=seasons, label=_("Season"), lookup_expr='year', help_text="", ) status = filters.ChoiceFilter( choices=FILTER_HARVEST_CHOICES, help_text="", ) pick_leader = filters.ModelChoiceFilter( queryset=AuthUser.objects.filter(is_staff=True), required=False, help_text="", ) trees = filters.ModelChoiceFilter(queryset=TreeType.objects.all(), label=_("Tree"), help_text="", required=False) property__neighborhood = filters.ModelChoiceFilter( queryset=Neighborhood.objects.all(), label=_("Neighborhood"), help_text="", required=False) class Meta: model = Harvest fields = { 'status': ['exact'], 'pick_leader': ['exact'], 'trees': ['exact'], 'property__neighborhood': ['exact'], 'start_date': ['exact'], }
class CharacterFilter(filters.FilterSet): book = filters.ModelChoiceFilter( queryset=models.Book.objects.all(), field_name="created_by_run__book", label="Book ID", widget=forms.TextInput, ) page_sequence = filters.NumberFilter( field_name="line__page__sequence", label="Page sequence" ) page_side = filters.ChoiceFilter( choices=models.Page.SPREAD_SIDE, field_name="line__page__side" ) line_sequence = filters.NumberFilter( field_name="line__sequence", label="Line sequence" ) sequence = filters.NumberFilter() created_by_run = filters.ModelChoiceFilter( queryset=models.CharacterRun.objects.all(), widget=forms.TextInput ) character_class = filters.ModelChoiceFilter( queryset=models.CharacterClass.objects.all(), widget=forms.TextInput ) human_character_class = filters.ModelChoiceFilter( queryset=models.CharacterClass.objects.all(), widget=forms.TextInput ) agreement = filters.ChoiceFilter( choices=( ("all", "all"), ("unknown", "unknown"), ("agreement", "agreement"), ("disagreement", "disagreement"), ), method="class_agreement", label="Machine/human class agreement", ) def class_agreement(self, queryset, name, value): if value == "unknown": return queryset.filter(human_character_class__isnull=True) elif value == "agreement": return queryset.filter(character_class__exact=F("human_character_class")) elif value == "disagreement": return queryset.exclude(character_class=F("human_character_class")).exclude( human_character_class__isnull=True ) else: return queryset
class UserFilter(filters.FilterSet): text_search = filters.CharFilter(method='filter_search') #fuzzy_text_search = filters.CharFilter(method='fuzzy_search') role = filters.ChoiceFilter(choices=User.USER_ROLE) # This requires pg_trgm be installed in Postgres... which would be a pain in a half on docker and it's not clear # trigram matching would really give any better results. # def fuzzy_search(self, queryset, name, value): # return queryset.annotate(similarity = TrigramSimilarity('name', value)).filter(similarity__gt=0.3)\ # .order_by('-similarity') def filter_search(self, queryset, name, value): #return queryset.annotate(search=SearchVector('name', 'username', 'email')).filter(search=value) # Thanks to https://www.mattlayman.com/blog/2017/postgres-search-django/ # `search` is the user's provided search string. # terms = [SearchQuery(term) for term in value.split()] # vector = SearchVector('email', 'name', 'username') # query = functools.reduce(operator.or_, terms) # queryset = queryset.annotate(rank=SearchRank(vector, query)).order_by('-rank') # queryset = queryset.filter(rank__gte=0.04) # combined earlier approaches using this great guide: http://rubyjacket.com/build/django-psql-fts.html return queryset.annotate(rank=SearchRank( SearchVector('name', 'username', 'email'), SearchQuery(value, search_type="websearch", config="english"))).order_by('-rank') class Meta: model = User fields = ['text_search', 'role'] #'fuzzy_text_search',
class BrokerAccountFilter(filters.FilterSet): id = filters.NumberFilter(name="id", label="ID", lookup_expr="exact") id_range = filters.RangeFilter(name="id", label="ID Between") broker = filters.CharFilter(name="broker__name__username", label="Broker name", lookup_expr='icontains') relation = filters.ChoiceFilter(choices=ACCOUNT_RELATION_CHOICES, label="Account Relation Choices") account_null = filters.BooleanFilter(name="account", label="Is Account Null", lookup_expr="isnull") account_number = filters.CharFilter(name="account__acount_number", label="Account Number", lookup_expr='exact') bank_name = filters.CharFilter(name="account__bank", label="Bank Name", lookup_expr='icontains') ifsc = filters.CharFilter(name="account__ifsc", label="IFSC Code", lookup_expr='icontains') created_on = filters.IsoDateTimeFilter(name="created_on", label="Created on") created_between = filters.DateTimeFromToRangeFilter( name="created_on", label="Created Between") class Meta: model = BrokerAccount fields = []
class InputFilter(filters.FilterSet): """ Provides useful filtering options for the :class:`~django_analyses.models.input.input.Input` model. """ key = filters.CharFilter( lookup_expr="icontains", label="Definition key contains (case-insensitive)", method="filter_key", ) input_type = filters.ChoiceFilter(choices=InputTypes.choices(), method="filter_input_type", label="Type") class Meta: model = Input fields = "run", "key" def filter_key(self, queryset, name, value): ids = [ inpt.id for inpt in queryset.all() if value in inpt.definition.key ] return queryset.filter(id__in=ids) def filter_input_type(self, queryset, name, value): ids = [ inpt.id for inpt in queryset.all() if inpt.get_type().name == value ] return queryset.filter(id__in=ids)
class BesluitTypeFilter(FilterSet): zaaktypen = filters.CharFilter( field_name="zaaktypen", method=m2m_filter, help_text=_( "ZAAKTYPE met ZAAKen die relevant kunnen zijn voor dit BESLUITTYPE" ), validators=[URLValidator()], ) informatieobjecttypen = filters.CharFilter( field_name="informatieobjecttypen", method=m2m_filter, help_text=_( "Het INFORMATIEOBJECTTYPE van informatieobjecten waarin besluiten van dit " "BESLUITTYPE worden vastgelegd."), validators=[URLValidator()], ) status = filters.ChoiceFilter( field_name="concept", method=status_filter, help_text=STATUS_HELP_TEXT, choices=StatusChoices.choices, ) class Meta: model = BesluitType fields = ("catalogus", "zaaktypen", "informatieobjecttypen", "status")
class ServiceFilter(filters.FilterSet): service_type = filters.ChoiceFilter(field_name='service_type', choices=SERVICE_CHOICES, method='filter_service_type') def filter_service_type(self, queryset, name, value): service_queryset = None if value == 'Procedure': service_queryset = Procedure.objects.all() elif value == 'Event': service_queryset = Event.objects.all() elif value == 'Survey': service_queryset = Survey.objects.all() elif value == 'Speciality': service_queryset = Speciality.objects.all() try: service_id_list = service_queryset.values_list('service__id', flat=True) except: return queryset.none() else: return queryset.filter(id__in=service_id_list) class Meta: model = Service fields = [ 'service_type', ]
class ApiLogFilter(filters.FilterSet): SERVICE_CHOICES = [ ('Heroku', 'Heroku'), ('Magento', 'Magento'), ('Mailgun', 'Mailgun'), ('PrintNode', 'PrintNode'), ('Sagepay', 'Sagepay'), ('Ship Theory', 'Ship Theory'), ('Xero', 'Xero'), ] api_service = filters.ChoiceFilter(field_name='api_service', label='Service Name', choices=SERVICE_CHOICES) date = filters.DateFilter( field_name='date', lookup_expr='lte', label='Date To', widget=forms.DateInput(attrs={ 'type': 'date', 'class': 'date-input', 'id': 'dateFromInput' })) response_code = filters.CharFilter(field_name='response_code', label='Response', lookup_expr='icontains') class Meta: model = ApiLog fields = ['process', 'api_service', 'response_code', 'date']
class RoomTimeFilter(filters.FilterSet): """ Filtering events depending on room in which event take place """ PERIOD_CHOICES = ( ("week", "week"), ("month", "month"), ("year", "year"), ) period = filters.ChoiceFilter(choices=PERIOD_CHOICES, method="filter_by_period", field_name="start") class Meta: model = Event fields = ( "period", ) def filter_by_period(self, queryset, name, value): d = Delorean(timezone="Asia/Bishkek") start = d.datetime end = start if value == "week": end = d.next_sunday().datetime if value == "month": end = (d.next_month().truncate("month") - timedelta(days=1)).datetime if value == "year": end = (d.next_year().truncate("year") - timedelta(days=1)).datetime return queryset.filter(Q(start_date__gte=start, start_date__lte=end))
class UserFilter(BaseFilterSet): system_or_org_role = filters.ChoiceFilter( choices=SystemOrOrgRole.choices, method='filter_system_or_org_role') class Meta: model = User fields = ('id', 'username', 'email', 'name', 'source', 'system_or_org_role') def filter_system_or_org_role(self, queryset, name, value): value = value.split('_') if len(value) == 1: role_type, value = None, value[0] else: role_type, value = value value = value.title() system_queries = Q(role=value) org_queries = Q(m2m_org_members__role=value, m2m_org_members__org_id=current_org.id) if not role_type: queries = system_queries | org_queries elif role_type == 'system': queries = system_queries elif role_type == 'org': queries = org_queries return queryset.filter(queries)
class CommentFilterSet(django_filters.FilterSet): """FilterSet for CommentViewSet.""" def get_content_type(): """Return list for `content_type` choices.""" item_list = [] content_list = ContentType.objects.all() for item in content_list: item_list.append((item.name, item.name)) return item_list def get_is_parent(self, queryset, name, value): """Filters queryset based on `is_parent` field.""" if value == True: queryset = queryset.filter(parent__isnull=True) else: queryset = queryset.filter(parent__isnull=False) return queryset is_parent = django_filters.BooleanFilter(method='get_is_parent') content_type = django_filters.ChoiceFilter( choices=get_content_type(), field_name='content_type__model', lookup_expr='iexact') object_id = django_filters.CharFilter(lookup_expr='iexact') class Meta: model = models.Comment fields = ['content_type', 'object_id', 'parent__id', 'is_parent']
class CustomerContractFilter(filters.FilterSet): id = filters.NumberFilter(name="id", label="ID", lookup_expr="exact") id_range = filters.RangeFilter(name="id", label="ID Between") customer_name = filters.CharFilter(name="customer__name__username", label="Customer name", lookup_expr="icontains") customer_name_null = filters.BooleanFilter(name="customer__name__username", label="Is Customer name Null", lookup_expr='isnull') customer_code = filters.CharFilter(name="customer__company_code", label="Customer name") customer_code_null = filters.BooleanFilter(name="customer__name__username", label="Is Customer name Null", lookup_expr="isnull") start_date_between = filters.DateTimeFromToRangeFilter( name="start_date", label="Start Date Between") billing_frequency = filters.ChoiceFilter(name="billing_frequency", choices=BILLING_FREQUENCY_CHOICES) created_on = filters.IsoDateTimeFilter(name="created_on", label="Created on") created_between = filters.DateTimeFromToRangeFilter( name="created_on", label="Created Between") class Meta: model = CustomerContract fields = []
class BusinessFilterSet(filters.FilterSet): status = filters.ChoiceFilter(choices=Business.events.STATUS_CHOICES) class Meta: model = Business fields = ['id', 'status', 'location__npa']
class InvoiceFilter(filters.FilterSet): class Meta: model = Invoice fields = ["organization"] organization = filters.CharFilter( field_name="organization", method="filter_organization_uuid", help_text=_("Organization's UUID"), required=True, ) start_due_date = filters.DateFilter(lookup_expr="gte", field_name="due_date") end_due_date = filters.DateFilter(lookup_expr="lte", field_name="due_date") payment_status = filters.ChoiceFilter( choices=Invoice.PAYMENT_STATUS_CHOICES, field_name="payment_status" ) def filter_organization_uuid(self, queryset, name, value): # pragma: no cover request = self.request try: organization = Organization.objects.get(uuid=value) authorization = organization.get_user_authorization(request.user) if not authorization.can_read: raise PermissionDenied() return queryset.filter(organization=organization) except Organization.DoesNotExist: raise NotFound(_("Organization {} does not exist").format(value)) except DjangoValidationError: raise NotFound(_("Invalid organization UUID"))
class PostFilter(filters.FilterSet): actual_only = filters.BooleanFilter( method='filter_actual_only', ) status = filters.ChoiceFilter( choices=Post.STATUSES, ) earlier = filters.DateTimeFilter( field_name='schedule', lookup_expr='lte', ) later = filters.DateTimeFilter( field_name='schedule', lookup_expr='gte', ) @staticmethod def filter_actual_only(queryset, _, value): if value: queryset = queryset.filter(status__lte=Post.READY) return queryset class Meta: model = Post fields = [ 'status', 'earlier', 'later', ]
class ContractorOrderFilter(OrderFilter): id = filters.NumberFilter(field_name="id", lookup_expr='contains') min_date = filters.DateTimeFilter(field_name="order__created", lookup_expr='gte') max_date = filters.DateTimeFilter(field_name="order__created", lookup_expr='lte') status = filters.ChoiceFilter(field_name="order__status", choices=OrderStatuses.ORDER_STATUSES) user_fio = filters.CharFilter(field_name="order__orderuser__contact_fio", lookup_expr='icontains') user_phone = filters.CharFilter(field_name="order__user_phone", lookup_expr='icontains') status_group = filters.NumberFilter(field_name='order__status_group', lookup_expr='exact') class Meta: model = ContractorOrder fields = ( 'id', 'min_date', 'max_date', 'status', 'user_fio', 'user_phone', 'status_group', )
class RecordFilter(filters.FilterSet): date_start__gte = filters.IsoDateTimeFilter(field_name='date_start', lookup_expr='gte') date_end__lte = filters.IsoDateTimeFilter(field_name='date_end', lookup_expr='lte') service_type = filters.ChoiceFilter(field_name='service_type', choices=SERVICE_CHOICES, method='filter_service_type') def filter_service_type(self, queryset, name, value): service_queryset = queryset.none() if value == 'Procedure': service_queryset = Procedure.objects.all() elif value == 'Event': service_queryset = Event.objects.all() elif value == 'Survey': service_queryset = Survey.objects.all() elif value == 'Speciality': service_queryset = Speciality.objects.all() service_id_list = service_queryset.values_list('service__id', flat=True) record_services = RecordService.objects.filter( service__id__in=service_id_list) record_id_list = record_services.values_list('record__id', flat=True) return queryset.filter(id__in=record_id_list) class Meta: model = Record fields = [ 'date_start', 'date_end', 'service_type', ]
class ProcedureStepFilter(filters.FilterSet): """ Provides useful filtering options for the :class:`~research.models.procedure_step.ProcedureStep` model. """ title = filters.LookupChoiceFilter(field_name="event__title", lookup_choices=LOOKUP_CHOICES) description = filters.LookupChoiceFilter(field_name="event__description", lookup_choices=LOOKUP_CHOICES) exclude_procedure = filters.ModelMultipleChoiceFilter( field_name="procedure", exclude=True, queryset=Procedure.objects.all()) event_type = filters.ChoiceFilter( choices=( ("measurementdefinition", "Measurement Definition"), ("task", "Task"), ), method="check_event_type", label="Event type:", ) content_type = filters.ChoiceFilter( choices=(("django_mri.Session", "MRI Session"), ), method="check_content_type", label="Measurement content type:", ) class Meta: model = ProcedureStep fields = ( "id", "index", "procedure", ) def check_event_type(self, queryset: QuerySet, name: str, value: str, *args, **kwargs) -> QuerySet: key = EVENT_TYPE_QUERY_KEY.format(event_type=value) return queryset.filter(**{key: False}) def check_content_type(self, queryset: QuerySet, name: str, value: str, *args, **kwargs) -> QuerySet: query = Q() values = value.lower().split(".") for part, value in zip(CONTENT_TYPE_PARTS, values): key = CONTENT_TYPE_QUERY_KEY.format(part=part) query |= Q(**{key: value}) return queryset.filter(query)
class EquipmentFilterSet(filters.FilterSet): category = filters.ChoiceFilter(field_name='category', choices=Equipment.CATEGORY_CHOICES, label='Filter equipments by a category') class Meta: model = Equipment fields = ["category"]
class HistoryFilter(filters.FilterSet): typus = filters.ChoiceFilter(choices=HistoryTypus.items(), method=filter_history_typus) date = ISODateTimeFromToRangeFilter(field_name='date') class Meta: model = History fields = ('group', 'store', 'users', 'typus', 'date')
class PraiseFilter(filters.FilterSet): type = filters.ChoiceFilter(choices=Collect.TYPE_CHOICES, label='点赞资源分类', required=True) class Meta: model = Praise fields = ('type', )