class WineFilter(django_filters.FilterSet): wine_name = django_filters.CharFilter(field_name='wine_name', label='Wine Name', lookup_expr='icontains') # Add description, heritage_site_category, region, sub_region and intermediate_region filters here region1 = django_filters.ModelChoiceFilter( field_name='region1__region1_name', label='Region', queryset=Region1.objects.all().order_by('region1_name'), lookup_expr='exact') variety = django_filters.ModelChoiceFilter( field_name='variety', label='Variety', queryset=Variety.objects.all().order_by('variety_name'), lookup_expr='exact') points = django_filters.NumericRangeFilter(field_name='points', label='Points', lookup_expr='range') price = django_filters.NumericRangeFilter(field_name='price', label='Price', lookup_expr='range') # Add date_inscribed filter here class Meta: model = Wine # form = SearchForm # fields [] is required, even if empty. fields = []
class BenthicPITFilterSet(BaseAPIFilterSet): interval_size = django_filters.NumericRangeFilter( field_name="interval_size") interval_start = django_filters.NumericRangeFilter( field_name="interval_start") class Meta: model = BenthicPIT fields = [ "transect", "transect__sample_event", "interval_size", "interval_start", ]
class ObsBeltFishFilterSet(BaseAPIFilterSet): size = django_filters.NumericRangeFilter(field_name="size") count = django_filters.NumericRangeFilter(field_name="count") class Meta: model = ObsBeltFish fields = [ "beltfish", "beltfish__transect", "beltfish__transect__sample_event", "fish_attribute", "size_bin", "include", "size", "count", ]
class ApplicationFilter(django_filters.FilterSet): gpa = django_filters.NumericRangeFilter( field_name="gpa", label="GPA (Between)", lookup_expr="range" ) application_number = django_filters.CharFilter( field_name="application_number", lookup_expr="icontains", label="Application Number", ) first_name = django_filters.CharFilter( field_name="first_name", lookup_expr="icontains", label="First Name" ) last_name = django_filters.CharFilter( field_name="last_name", lookup_expr="icontains", label="Last Name" ) application_status = django_filters.ChoiceFilter( field_name="application_status", label="Application Status", choices=FILTER_CHOICES, ) class Meta: model = HighSchoolApplication fields = [ "gpa", "application_number", "first_name", "last_name", "application_status", "program", ]
class FishBeltTransectFilterSet(BaseAPIFilterSet): len_surveyed = django_filters.NumericRangeFilter(field_name='len_surveyed') class Meta: model = FishBeltTransect fields = [ 'beltfish_method', 'sample_event', 'len_surveyed', 'width', ]
class ProductFilter(django_filters.FilterSet): # seller_id = django_filters.NumberFilter(lookup_expr='exact') brand = django_filters.CharFilter(lookup_expr='icontains') name = django_filters.CharFilter(lookup_expr='icontains') rank = django_filters.NumberFilter(lookup_expr='lt') category = django_filters.ModelChoiceFilter( queryset=Category.objects.all(), ) price = django_filters.NumericRangeFilter() class Meta: model = Products fields = ['brand', 'name', 'rank']
class MedicFilter(django_filters.FilterSet): cost = django_filters.NumericRangeFilter(name='cost') #cost__gt = django_filters.NumberFilter(name='cost', lookup_expr='amount__gt') #cost__lt = django_filters.NumberFilter(name='cost', lookup_expr='amount__lt') class Meta: model = Profile fields = [ 'genre', 'city', 'cost', ]
class BenthicTransectFilterSet(BaseAPIFilterSet): len_surveyed = django_filters.NumericRangeFilter(field_name='len_surveyed') class Meta: model = BenthicTransect fields = [ 'benthiclit_method', 'benthicpit_method', 'habitatcomplexity_method', 'sample_event', 'len_surveyed', ]
class ObsBenthicLITFilterSet(BaseAPIFilterSet): length = django_filters.NumericRangeFilter(field_name='length') class Meta: model = ObsBenthicLIT fields = [ 'benthiclit', 'benthiclit__transect', 'benthiclit__transect__sample_event', 'attribute', 'include', 'length', ]
class CatalogFilter(django_filters.FilterSet): genre_id = django_filters.ModelMultipleChoiceFilter( queryset=Genre.objects.all(), widget=forms.CheckboxSelectMultiple) author = django_filters.ModelMultipleChoiceFilter( queryset=Author.objects.all(), widget=forms.CheckboxSelectMultiple) publisher_id = django_filters.ModelMultipleChoiceFilter( queryset=Publisher.objects.all(), widget=forms.CheckboxSelectMultiple) price = django_filters.NumericRangeFilter(name='price', lookup_expr='range') class Meta(object): model = Book fields = ['genre', 'author', 'publisher', 'price']
class SampleEventFilterSet(BaseAPIFilterSet): sample_date = django_filters.DateTimeFromToRangeFilter( field_name='sample_date') depth = django_filters.NumericRangeFilter(field_name='depth') class Meta: model = SampleEvent fields = [ 'site', 'management', 'sample_date', 'sample_time', 'depth', 'visibility', 'current', 'relative_depth', 'tide', ]
class DateFilter(filters.FilterSet): date = filters.DateTimeFromToRangeFilter(field_name="date") event__title = filters.CharFilter(lookup_expr='icontains') event__type = filters.CharFilter(lookup_expr='icontains') event__promoter = filters.CharFilter(lookup_expr='icontains') event__tags = CharArrayFilter(method='filter_by_event_tags') venue__name = filters.CharFilter(lookup_expr='icontains') venue__address = filters.CharFilter(lookup_expr='icontains') venue__capacity = filters.NumericRangeFilter(field_name='venue__capacity') def filter_by_event_tags(self, queryset, name, value): lookup = "__".join([name, "overlap"]) queryset = queryset.filter(**{lookup: value}) return queryset class Meta: model = Date fields = []
class PManagementFilterSet(BaseAPIFilterSet): predecessor = NullableUUIDFilter(field_name='predecessor') compliance = NullableUUIDFilter(field_name='compliance') est_year = django_filters.NumericRangeFilter(field_name='est_year') class Meta: model = Management fields = [ 'predecessor', 'parties', 'compliance', 'est_year', 'no_take', 'periodic_closure', 'open_access', 'size_limits', 'gear_restriction', 'species_restriction', ]
class ManagementFilterSet(BaseAPIFilterSet): project = django_filters.UUIDFilter( field_name='sampleevent__site__project', distinct=True, label='Associated with project') predecessor = NullableUUIDFilter(field_name='predecessor') compliance = NullableUUIDFilter(field_name='compliance') est_year = django_filters.NumericRangeFilter(field_name='est_year') unique = django_filters.CharFilter(method='filter_unique') exclude_projects = django_filters.CharFilter(method='filter_not_projects') class Meta: model = Management fields = [ 'project', 'predecessor', 'parties', 'compliance', 'est_year', 'no_take', 'periodic_closure', 'open_access', 'size_limits', 'gear_restriction', 'species_restriction', 'unique', 'exclude_projects', ] def filter_unique(self, queryset, name, value): unique_fields = ( 'name', 'name_secondary', 'parties', 'compliance_id', 'est_year', 'boundary', 'size', 'no_take', 'periodic_closure', 'open_access', 'size_limits', 'gear_restriction', 'species_restriction', ) project_id = value group_by = ','.join(['"{}"'.format(uf) for uf in unique_fields]) sql = """ "management".id::text IN ( SELECT id FROM ( SELECT (agg_managements.ids)[1] AS id, project_ids FROM ( SELECT ARRAY_AGG(id::text) AS ids, ARRAY_AGG(project_id::text) AS project_ids FROM management LEFT JOIN ( SELECT array_to_string(ARRAY_AGG(management_party.name ORDER BY management_party.name), ',') AS parties, management_parties.management_id FROM management_party INNER JOIN management_parties ON (management_parties.managementparty_id = management_party.id) GROUP BY management_parties.management_id ) AS mgmt_parties ON (mgmt_parties.management_id = management.id) GROUP BY {} ) AS agg_managements WHERE NOT('{}' = ANY(agg_managements.project_ids)) ) AS management_ids ) """.format(group_by, project_id) return queryset.extra(where=[sql]) def filter_not_projects(self, queryset, name, value): value_list = [v.strip() for v in value.split(u',')] return queryset.exclude(project__in=value_list)
class EmployeeFilter(django_filters.FilterSet): first_eduction = django_filters.ChoiceFilter( label=u'第一学历', choices=qualification_choices, method='first_eduction_filter') contracts_duration = django_filters.ChoiceFilter( label=u'合同期限', choices=contract_durtaion_choice, method='contracts_duration_filter') age = django_filters.NumericRangeFilter( label=u'年龄', method='age_filter', ) work_age = django_filters.NumericRangeFilter( label=u'工龄', method='work_age_filter', ) local_age = django_filters.NumericRangeFilter( label=u'行龄', method='local_age_filter', ) class Meta: model = Employee fields = [ 'department', 'department__type', 'gender', 'employee_type', 'political_status', 'contracts_duration', 'first_eduction', 'age', 'work_age', 'local_age' ] @staticmethod def contracts_duration_filter(self, qs, value): q = self if value is not None: return q.filter(employee_number__in=[ o.employee_number for o in q if value == o.contracts.duration ]) @staticmethod def first_eduction_filter(self, qs, value): q = self if value is not None: return q.filter(employee_number__in=[ o.employee_number for o in q if value == o.first_eduction_qualification() ]) @staticmethod def age_filter(self, qs, value): q = self if value.start is not None and value.stop is not None: return q.filter(employee_number__in=[ o.employee_number for o in q if value.start <= o.age() <= value.stop ]) elif value.start is not None: return q.filter(employee_number__in=[ o.employee_number for o in q if value.start <= o.age() ]) elif value.stop is not None: return q.filter(employee_number__in=[ o.employee_number for o in q if o.age() <= value.stop ]) else: return q @staticmethod def work_age_filter(self, qs, value): q = self if value.start is not None and value.stop is not None: return q.filter(employee_number__in=[ o.employee_number for o in q if value.start <= o.work_age() <= value.stop ]) elif value.start is not None: return q.filter(employee_number__in=[ o.employee_number for o in q if value.start <= o.work_age() ]) elif value.stop is not None: return q.filter(employee_number__in=[ o.employee_number for o in q if o.work_age() <= value.stop ]) else: return q @staticmethod def local_age_filter(self, qs, value): q = self if value.start is not None and value.stop is not None: return q.filter(employee_number__in=[ o.employee_number for o in q if value.start <= o.local_age() <= value.stop ]) elif value.start is not None: return q.filter(employee_number__in=[ o.employee_number for o in q if value.start <= o.local_age() ]) elif value.stop is not None: return q.filter(employee_number__in=[ o.employee_number for o in q if o.local_age() <= value.stop ]) else: return q
class SiteListFilter(django_filters.FilterSet): # url = reverse('vocabs-ac:specific-concept-ac', kwargs={'schema': 'archenttype'}) name = django_filters.CharFilter( lookup_expr='icontains', help_text=Site._meta.get_field('name').help_text, label=Site._meta.get_field('name').verbose_name) alt_name = django_filters.ModelMultipleChoiceFilter( queryset=AltName.objects.all(), help_text=Site._meta.get_field('alt_name').help_text, label=Site._meta.get_field('alt_name').verbose_name, widget=autocomplete.Select2Multiple( url="/archiv-ac/altname-autocomplete-no-create", )) identifier = django_filters.CharFilter( lookup_expr='icontains', help_text=Site._meta.get_field('identifier').help_text, label=Site._meta.get_field('identifier').verbose_name) # has_research_activity = django_filters.ModelMultipleChoiceFilter( # queryset=ResearchEvent.objects.all(), # name='has_research_activity', # label="Research activity" # ) cadastral_community__ctnam = django_filters.CharFilter( lookup_expr='icontains', help_text="Country", label="Country", widget=autocomplete.Select2(url='shapes-ac:countries-ac', )) cadastral_community__nuts2nam = django_filters.CharFilter( lookup_expr='icontains', help_text="Counties", label="Counties", widget=autocomplete.Select2(url='shapes-ac:counties-ac', )) cadastral_community__nuts3nam = django_filters.CharFilter( lookup_expr='icontains', help_text="Regions", label="Regions", widget=autocomplete.Select2(url='shapes-ac:regions-ac', )) cadastral_community = django_filters.ModelMultipleChoiceFilter( queryset=Municipality.objects.exclude(has_sites=None), help_text=Site._meta.get_field('cadastral_community').help_text, label=Site._meta.get_field('cadastral_community').verbose_name, widget=autocomplete.Select2Multiple( url='shapes-ac:municipality-autocomplete-search', )) cadastral_number = django_filters.CharFilter( lookup_expr='icontains', help_text=Site._meta.get_field('cadastral_number').help_text, label=Site._meta.get_field('cadastral_number').verbose_name) heritage_number = django_filters.CharFilter( lookup_expr='icontains', help_text=Site._meta.get_field('heritage_number').help_text, label=Site._meta.get_field('heritage_number').verbose_name) plot_number = django_filters.CharFilter( lookup_expr='icontains', help_text=Site._meta.get_field('plot_number').help_text, label=Site._meta.get_field('plot_number').verbose_name) ownership = django_filters.ChoiceFilter( choices=SITE_OWNERSHIP, help_text=Site._meta.get_field('ownership').help_text, label=Site._meta.get_field('ownership').verbose_name) other_period = django_filters.ModelMultipleChoiceFilter( queryset=SkosConcept.objects.filter( scheme__dc_title__icontains="other-present-archaeological-period"), help_text=Site._meta.get_field('other_period').help_text, label=Site._meta.get_field('other_period').verbose_name, method=generous_concept_filter, widget=autocomplete.Select2Multiple( url= "/vocabs-ac/specific-concept-ac/other-present-archaeological-period", )) accessibility = django_filters.ChoiceFilter( choices=SITE_ACCESSIBILITY, help_text=Site._meta.get_field('accessibility').help_text, label=Site._meta.get_field('accessibility').verbose_name) visibility = django_filters.ChoiceFilter( choices=SITE_VISIBILITY, help_text=Site._meta.get_field('visibility').help_text, label=Site._meta.get_field('visibility').verbose_name) infrastructure = django_filters.ChoiceFilter( choices=SITE_INFRASTRUCTURE, help_text=Site._meta.get_field('infrastructure').help_text, label=Site._meta.get_field('infrastructure').verbose_name) long_term_management = django_filters.ChoiceFilter( choices=SITE_LONGTERMMANGEMENT, help_text=Site._meta.get_field('long_term_management').help_text, label=Site._meta.get_field('long_term_management').verbose_name) potential_surrounding = django_filters.ChoiceFilter( choices=SITE_POTENTIALSURROUNDINGS, help_text=Site._meta.get_field('potential_surrounding').help_text, label=Site._meta.get_field('potential_surrounding').verbose_name) # museum = django_filters.ModelMultipleChoiceFilter( # queryset=Institution.objects.all(), # help_text=Site._meta.get_field('museum').help_text, # label=Site._meta.get_field('museum').verbose_name, # ) # #################### Research Activity Fields #################### has_research_activity__start_date = django_filters.DateFilter( lookup_expr='gte', help_text=ResearchEvent._meta.get_field('start_date').help_text, label=ResearchEvent._meta.get_field('start_date').verbose_name) has_research_activity__end_date = django_filters.DateFilter( lookup_expr='lte', help_text=ResearchEvent._meta.get_field('end_date').help_text, label=ResearchEvent._meta.get_field('end_date').verbose_name) has_research_activity__responsible_researcher = django_filters.ModelMultipleChoiceFilter( queryset=Person.objects.all(), help_text=ResearchEvent._meta.get_field( 'responsible_researcher').help_text, label=ResearchEvent._meta.get_field( 'responsible_researcher').verbose_name) has_research_activity__responsible_institution = django_filters.ModelMultipleChoiceFilter( queryset=Institution.objects.all(), help_text=ResearchEvent._meta.get_field( 'responsible_institution').help_text, label=ResearchEvent._meta.get_field( 'responsible_institution').verbose_name) has_research_activity__research_type = django_filters.ModelChoiceFilter( queryset=SkosConcept.objects.filter( scheme__dc_title__icontains="research-type"), help_text=ResearchEvent._meta.get_field('research_type').help_text, label=ResearchEvent._meta.get_field('research_type').verbose_name, ) has_research_activity__research_method = django_filters.ModelMultipleChoiceFilter( queryset=SkosConcept.objects.filter( scheme__dc_title__icontains="research-methods"), help_text=ResearchEvent._meta.get_field('research_method').help_text, label=ResearchEvent._meta.get_field('research_method').verbose_name, method=generous_concept_filter, widget=autocomplete.Select2Multiple( url="/vocabs-ac/specific-concept-ac/research-methods", )) has_research_activity__research_question = django_filters.ModelMultipleChoiceFilter( queryset=ResearchQuestion.objects.all(), help_text=ResearchEvent._meta.get_field('research_question').help_text, label=ResearchEvent._meta.get_field('research_question').verbose_name) has_research_activity__generation_data_set = django_filters.DateFilter( lookup_expr='exact', help_text=ResearchEvent._meta.get_field( 'generation_data_set').help_text, label=ResearchEvent._meta.get_field( 'generation_data_set').verbose_name) # #################### Arch.Entity Fields #################### has_archent__ent_type = django_filters.ModelMultipleChoiceFilter( queryset=SkosConcept.objects.filter( scheme__dc_title__icontains="archaeological-entity-type"), help_text=ArchEnt._meta.get_field('ent_type').help_text, label=ArchEnt._meta.get_field('ent_type').verbose_name, method=generous_concept_filter, widget=autocomplete.Select2Multiple( url="/vocabs-ac/specific-concept-ac/archaeological-entity-type", )) has_archent__burial_type = django_filters.ModelMultipleChoiceFilter( queryset=SkosConcept.objects.filter( scheme__dc_title__icontains="burial-type"), help_text=ArchEnt._meta.get_field('burial_type').help_text, label=ArchEnt._meta.get_field('burial_type').verbose_name, method=generous_concept_filter, widget=forms.CheckboxSelectMultiple( attrs={'class': 'chbx-select-multi'})) has_archent__settlement_fortification = django_filters.ModelMultipleChoiceFilter( queryset=SkosConcept.objects.filter( scheme__dc_title__icontains="settlement-fortification"), help_text=ArchEnt._meta.get_field( 'settlement_fortification').help_text, label=ArchEnt._meta.get_field('settlement_fortification').verbose_name, method=generous_concept_filter, widget=forms.CheckboxSelectMultiple( attrs={'class': 'chbx-select-multi'})) has_archent__settlement_occupation = django_filters.ModelMultipleChoiceFilter( queryset=SkosConcept.objects.filter( scheme__dc_title__icontains="settlement-occupation"), help_text=ArchEnt._meta.get_field('settlement_occupation').help_text, label=ArchEnt._meta.get_field('settlement_occupation').verbose_name, method=generous_concept_filter, widget=forms.CheckboxSelectMultiple( attrs={'class': 'chbx-select-multi'})) has_archent__topography = django_filters.ModelMultipleChoiceFilter( queryset=SkosConcept.objects.filter( scheme__dc_title__icontains="topography"), help_text=ArchEnt._meta.get_field('topography').help_text, label=ArchEnt._meta.get_field('topography').verbose_name, method=generous_concept_filter, widget=forms.CheckboxSelectMultiple( attrs={'class': 'chbx-select-multi'})) has_archent__type_certainty = django_filters.ChoiceFilter( help_text=ArchEnt._meta.get_field('type_certainty').help_text, label=ArchEnt._meta.get_field('type_certainty').verbose_name, choices=ARCHENT_CERTAINTY) has_archent__dating_certainty = django_filters.ChoiceFilter( help_text=ArchEnt._meta.get_field('dating_certainty').help_text, label=ArchEnt._meta.get_field('dating_certainty').verbose_name, choices=ARCHENT_CERTAINTY) has_archent__location_certainty = django_filters.ChoiceFilter( help_text=ArchEnt._meta.get_field('location_certainty').help_text, label=ArchEnt._meta.get_field('location_certainty').verbose_name, choices=ARCHENT_CERTAINTY) has_archent__period = django_filters.ModelMultipleChoiceFilter( queryset=Period.objects.all(), help_text=ArchEnt._meta.get_field('period').help_text, label=ArchEnt._meta.get_field('period').verbose_name, widget=autocomplete.Select2Multiple( url="/archiv-ac/period-autocomplete", )) site_start_date = django_filters.RangeFilter(help_text="Year not before", label="Earliest date (BC)") site_end_date = django_filters.RangeFilter(help_text="Year not after", label="Latest date (BC)") # #################### Monument Protection Fields #################### has_monument_protection__current_land_use = django_filters.ModelMultipleChoiceFilter( queryset=SkosConcept.objects.filter( scheme__dc_title__icontains="current-land-use"), help_text=MonumentProtection._meta.get_field( 'current_land_use').help_text, label=MonumentProtection._meta.get_field( 'current_land_use').verbose_name, method=generous_concept_filter, widget=autocomplete.Select2Multiple( url="/vocabs-ac/specific-concept-ac/current-land-use", )) has_monument_protection__heritage_status = django_filters.ChoiceFilter( help_text=MonumentProtection._meta.get_field( 'heritage_status').help_text, label=MonumentProtection._meta.get_field( 'heritage_status').verbose_name, choices=HERITAGE_STATUS_CHOICES, distinct=True) has_monument_protection__natural_heritage_status = django_filters.ChoiceFilter( help_text=MonumentProtection._meta.get_field( 'natural_heritage_status').help_text, label=MonumentProtection._meta.get_field( 'natural_heritage_status').verbose_name, choices=HERITAGE_STATUS_CHOICES, distinct=True) has_monument_protection__threats = django_filters.ModelMultipleChoiceFilter( queryset=SkosConcept.objects.filter( scheme__dc_title__icontains="threats"), help_text=MonumentProtection._meta.get_field('threats').help_text, label=MonumentProtection._meta.get_field('threats').verbose_name, method=generous_concept_filter, widget=forms.CheckboxSelectMultiple( attrs={'class': 'chbx-select-multi'})) temp_extent = django_filters.NumericRangeFilter( lookup_expr="contains", label="Site falls temporally within", help_text="Show only sites dated to a specific time span\ (e.g. sites dated between -1200 and -600)") temp_extent_intersects = django_filters.NumericRangeFilter( field_name="temp_extent", lookup_expr="overlap", label="Site intersects temporally with", help_text= "Show all sites which dating intersects with the defined time span\ (e.g. sites partly dated between -1200 and -600 BC).") class Meta: model = Site exclude = [ 'polygon', 'centroid', ]
class AccountItemsBoughtFilter(filters.FilterSet): date_range = django_filters.DateFromToRangeFilter(name='purchase_date') unit_price_range = django_filters.NumericRangeFilter(name='unit_price') class Meta: model = Product fields = ['product_category','unit_price','purchase_date','unit_price_range']
class WineFilter(django_filters.FilterSet): name = django_filters.CharFilter(lookup_expr='icontains', widget=forms.TextInput( attrs={ 'placeholder': 'Name' } ) ) winery = django_filters.CharFilter(lookup_expr='icontains', widget=forms.TextInput( attrs={ 'placeholder': 'Winery' } ) ) vintage = django_filters.ChoiceFilter(choices=Wine.VINTAGE, empty_label="Vintage", widget=forms.Select( attrs={ 'style': 'font-family: Times New Roman; color:#6c757d;', } ) ) bottle = django_filters.ChoiceFilter(choices=Wine.BOTTLE, empty_label="Bottle", widget=forms.Select( attrs={ 'style': 'font-family: Times New Roman; color:#6c757d;', } ) ) closure = django_filters.ChoiceFilter(choices=Wine.CLOSURE, empty_label="Closure", widget=forms.Select( attrs={ 'style': 'font-family: Times New Roman; color:#6c757d;', } ) ) region = django_filters.CharFilter(lookup_expr='icontains', widget=forms.TextInput( attrs={ 'placeholder': 'Region' } ) ) type = django_filters.ModelChoiceFilter(queryset=Type.objects.all(), empty_label="Style", widget=forms.Select( attrs={ 'style': 'font-family: Times New Roman; color:#6c757d;', } ) ) country = django_filters.ModelChoiceFilter(queryset=Country.objects.all(), empty_label="Country", widget=forms.Select( attrs={ 'style': 'font-family: Times New Roman; color:#6c757d;', } ) ) grapes = django_filters.ModelMultipleChoiceFilter(queryset=Grapes.objects.all(), widget=FilteredSelectMultiple("Grapes", False, attrs={'rows':'10'})) bought_from = django_filters.CharFilter(lookup_expr='icontains', widget=forms.TextInput( attrs={ 'placeholder': 'Bought from' } ) ) rating = django_filters.NumericRangeFilter(label="Rating range", lookup_expr='range', widget=django_filters.widgets.RangeWidget( attrs={ 'placeholder': 'Rating starts/ends at' } ) ) abv = django_filters.NumericRangeFilter(label="ABV Range", lookup_expr='range', widget=django_filters.widgets.RangeWidget( attrs={ 'placeholder': 'ABV starts/ends at' } ) ) price = django_filters.NumericRangeFilter(label="Price range", lookup_expr='range', widget=django_filters.widgets.RangeWidget( attrs={ 'placeholder': 'Price starts/ends at' } ) ) class Meta: model = Wine fields = ['name', 'winery', 'vintage', 'bottle', 'closure', 'region', 'type', 'country', 'grapes', 'bought_from', 'rating', 'abv', 'price'] exclude = ['colour', 'aroma', 'taste', 'overall', 'image', 'posted_on', 'drink_by', 'cellar', 'acquired', 'like',]
class MovieFilter(django_filters.FilterSet): id = django_filters.NumberFilter(method='filter_id') title = django_filters.CharFilter(method='filter_title') released_year = django_filters.NumericRangeFilter(method='filter_year') rating = django_filters.RangeFilter(method='filter_rating') class Meta: model = Movie fields = ['id', 'rating', 'released_year', 'title', 'genre'] def filter_id(self, queryset, name, value): if not value: return queryset if not queryset.filter(id=value).exists(): self.scrap_movie_by_id(value) return queryset.filter(id=value) def filter_title(self, queryset, name, value): if not value: return queryset if not queryset.filter(title=value).exists(): self.scrap_movie_by_title(value) return queryset.filter(title=value) def filter_rating(self, queryset, name, value): query_condition = Q() start = 0 stop = 10 if not value: return queryset if value.start: start = value.start query_condition.add(Q(rating__gte=start), Q.AND) if value.stop: stop = value.stop query_condition.add(Q(rating__lte=stop), Q.AND) if not queryset.filter(query_condition).exists(): self.scrap_movie_by_rating(start, stop) return queryset.filter(query_condition) def filter_year(self, queryset, name, value): query_condition = Q() start = value.start stop = value.stop if not value: return queryset if start and not stop: query_condition.add(Q(released_year__year=start), Q.AND) if stop and not start: query_condition.add(Q(released_year__year=stop), Q.AND) if start and stop: query_condition.add(Q(released_year__year__range=[start, stop]), Q.AND) if not queryset.filter(query_condition).exists(): self.scrap_movie_by_year(start, stop) return queryset.filter(query_condition) def scrap_movie_by_id(self, id): movie = MV() m = movie.details(id) self.set_data(m) # def scrap_movie_by_title(self, title): # import urllib2 # from bs4 import BeautifulSoup # page = urllib2.urlopen(url + '?title=' + title) # print page, 'page' # soup = BeautifulSoup(page, 'html.parser') # print soup # all = soup.find_all('div', attrs={'class': 'item poster card'}) # for i in all: # disc = i.find('p', attrs={'class': 'overview'}).text # rating = i.find('div', attrs={'class': 'user_score_chart'})['data-percent'] # rating = float(rating) / 10 # movie = i.find('a', attrs={'class': 'title result'}) # date = datetime.strptime(movie.findNext('span').text.split(',')[1], " %Y") # title = movie['title'] # pk = movie['id'].split('_')[1] # Movie.objects.create(id=pk, title=title, discription=disc, released_year=date, # rating=rating) def scrap_movie_by_title(self, title): movie = MV() res = movie.search(title) for m in res: self.set_data(m) def scrap_movie_by_year(self, start, stop): discover = Discover() discover_params = dict() if start: gte_year = datetime.strptime(str(start), "%Y") discover_params['primary_release_date.gte'] = gte_year if stop: lte_year = datetime.strptime(str(stop), "%Y") discover_params['primary_release_date.lte'] = lte_year try: movie = discover.discover_movies(discover_params) for m in movie: self.set_data(m) except Exception as e: raise TMDbException("Connection error to imdb api server") def scrap_movie_by_rating(self, start, stop): discover = Discover() movie = discover.discover_movies({ 'vote_average.gte': start, 'vote_average.lte': stop }) for m in movie: self.set_data(m) def set_data(self, m): data = dict() data['id'] = m.id data['released_year'] = datetime.strptime(m.release_date.split('-')[0], "%Y") \ if m.release_date else datetime.now() data['rating'] = m.vote_average if m.vote_average is not 0 else 10.0 data['title'] = m.title data['discription'] = m.overview Movie.objects.get_or_create(**data)