Exemple #1
0
class PrefixFilter(CustomFieldFilterSet, django_filters.FilterSet):
    id__in = NumericInFilter(name='id', lookup_expr='in')
    q = django_filters.CharFilter(
        method='search',
        label='Search',
    )
    parent = django_filters.CharFilter(
        method='search_by_parent',
        label='Parent prefix',
    )
    mask_length = django_filters.NumberFilter(
        method='filter_mask_length',
        label='Mask length',
    )
    vrf_id = NullableModelMultipleChoiceFilter(
        name='vrf_id',
        queryset=VRF.objects.all(),
        label='VRF',
    )
    vrf = NullableModelMultipleChoiceFilter(
        name='vrf',
        queryset=VRF.objects.all(),
        to_field_name='rd',
        label='VRF (RD)',
    )
    tenant_id = NullableModelMultipleChoiceFilter(
        name='tenant',
        queryset=Tenant.objects.all(),
        label='Tenant (ID)',
    )
    tenant = NullableModelMultipleChoiceFilter(
        name='tenant',
        queryset=Tenant.objects.all(),
        to_field_name='slug',
        label='Tenant (slug)',
    )
    site_id = NullableModelMultipleChoiceFilter(
        name='site',
        queryset=Site.objects.all(),
        label='Site (ID)',
    )
    site = NullableModelMultipleChoiceFilter(
        name='site',
        queryset=Site.objects.all(),
        to_field_name='slug',
        label='Site (slug)',
    )
    vlan_id = NullableModelMultipleChoiceFilter(
        name='vlan',
        queryset=VLAN.objects.all(),
        label='VLAN (ID)',
    )
    vlan_vid = django_filters.NumberFilter(
        name='vlan__vid',
        label='VLAN number (1-4095)',
    )
    role_id = NullableModelMultipleChoiceFilter(
        name='role',
        queryset=Role.objects.all(),
        label='Role (ID)',
    )
    role = NullableModelMultipleChoiceFilter(
        name='role',
        queryset=Role.objects.all(),
        to_field_name='slug',
        label='Role (slug)',
    )

    class Meta:
        model = Prefix
        fields = ['family', 'status']

    def search(self, queryset, name, value):
        if not value.strip():
            return queryset
        qs_filter = Q(description__icontains=value)
        try:
            prefix = str(IPNetwork(value.strip()).cidr)
            qs_filter |= Q(prefix__net_contains_or_equals=prefix)
        except AddrFormatError:
            pass
        return queryset.filter(qs_filter)

    def search_by_parent(self, queryset, name, value):
        value = value.strip()
        if not value:
            return queryset
        try:
            query = str(IPNetwork(value).cidr)
            return queryset.filter(prefix__net_contained_or_equal=query)
        except AddrFormatError:
            return queryset.none()

    def filter_mask_length(self, queryset, name, value):
        if not value:
            return queryset
        return queryset.filter(prefix__net_mask_length=value)
Exemple #2
0
class MessageFilter(GenericDateFilterSet):
    since = django_filters.NumberFilter(name='id', lookup_expr='gt')

    class Meta:
        model = Message
        fields = ('user', 'channel', 'since')
Exemple #3
0
class RegionFilter(django_filters.FilterSet):
    parent = django_filters.NumberFilter()

    class Meta:
        model = Region
        fields = ('kind', 'subdomain', 'parent')
Exemple #4
0
class DeviceFilter(CustomFieldFilterSet):
    id__in = NumericInFilter(field_name='id', lookup_expr='in')
    q = django_filters.CharFilter(
        method='search',
        label='Search',
    )
    manufacturer_id = django_filters.ModelMultipleChoiceFilter(
        field_name='device_type__manufacturer',
        queryset=Manufacturer.objects.all(),
        label='Manufacturer (ID)',
    )
    manufacturer = django_filters.ModelMultipleChoiceFilter(
        field_name='device_type__manufacturer__slug',
        queryset=Manufacturer.objects.all(),
        to_field_name='slug',
        label='Manufacturer (slug)',
    )
    device_type_id = django_filters.ModelMultipleChoiceFilter(
        queryset=DeviceType.objects.all(),
        label='Device type (ID)',
    )
    role_id = django_filters.ModelMultipleChoiceFilter(
        field_name='device_role_id',
        queryset=DeviceRole.objects.all(),
        label='Role (ID)',
    )
    role = django_filters.ModelMultipleChoiceFilter(
        field_name='device_role__slug',
        queryset=DeviceRole.objects.all(),
        to_field_name='slug',
        label='Role (slug)',
    )
    tenant_id = django_filters.ModelMultipleChoiceFilter(
        queryset=Tenant.objects.all(),
        label='Tenant (ID)',
    )
    tenant = django_filters.ModelMultipleChoiceFilter(
        field_name='tenant__slug',
        queryset=Tenant.objects.all(),
        to_field_name='slug',
        label='Tenant (slug)',
    )
    platform_id = django_filters.ModelMultipleChoiceFilter(
        queryset=Platform.objects.all(),
        label='Platform (ID)',
    )
    platform = django_filters.ModelMultipleChoiceFilter(
        field_name='platform__slug',
        queryset=Platform.objects.all(),
        to_field_name='slug',
        label='Platform (slug)',
    )
    name = NullableCharFieldFilter()
    asset_tag = NullableCharFieldFilter()
    region_id = django_filters.NumberFilter(
        method='filter_region',
        field_name='pk',
        label='Region (ID)',
    )
    region = django_filters.CharFilter(
        method='filter_region',
        field_name='slug',
        label='Region (slug)',
    )
    site_id = django_filters.ModelMultipleChoiceFilter(
        queryset=Site.objects.all(),
        label='Site (ID)',
    )
    site = django_filters.ModelMultipleChoiceFilter(
        field_name='site__slug',
        queryset=Site.objects.all(),
        to_field_name='slug',
        label='Site name (slug)',
    )
    rack_group_id = django_filters.ModelMultipleChoiceFilter(
        field_name='rack__group',
        queryset=RackGroup.objects.all(),
        label='Rack group (ID)',
    )
    rack_id = django_filters.ModelMultipleChoiceFilter(
        field_name='rack',
        queryset=Rack.objects.all(),
        label='Rack (ID)',
    )
    cluster_id = django_filters.ModelMultipleChoiceFilter(
        queryset=Cluster.objects.all(),
        label='VM cluster (ID)',
    )
    model = django_filters.ModelMultipleChoiceFilter(
        field_name='device_type__slug',
        queryset=DeviceType.objects.all(),
        to_field_name='slug',
        label='Device model (slug)',
    )
    status = django_filters.MultipleChoiceFilter(choices=DEVICE_STATUS_CHOICES,
                                                 null_value=None)
    is_full_depth = django_filters.BooleanFilter(
        field_name='device_type__is_full_depth',
        label='Is full depth',
    )
    mac_address = django_filters.CharFilter(
        method='_mac_address',
        label='MAC address',
    )
    has_primary_ip = django_filters.BooleanFilter(
        method='_has_primary_ip',
        label='Has a primary IP',
    )
    virtual_chassis_id = django_filters.ModelMultipleChoiceFilter(
        field_name='virtual_chassis',
        queryset=VirtualChassis.objects.all(),
        label='Virtual chassis (ID)',
    )
    console_ports = django_filters.BooleanFilter(
        method='_console_ports',
        label='Has console ports',
    )
    console_server_ports = django_filters.BooleanFilter(
        method='_console_server_ports',
        label='Has console server ports',
    )
    power_ports = django_filters.BooleanFilter(
        method='_power_ports',
        label='Has power ports',
    )
    power_outlets = django_filters.BooleanFilter(
        method='_power_outlets',
        label='Has power outlets',
    )
    interfaces = django_filters.BooleanFilter(
        method='_interfaces',
        label='Has interfaces',
    )
    pass_through_ports = django_filters.BooleanFilter(
        method='_pass_through_ports',
        label='Has pass-through ports',
    )
    tag = TagFilter()

    class Meta:
        model = Device
        fields = ['serial', 'position']

    def search(self, queryset, name, value):
        if not value.strip():
            return queryset
        return queryset.filter(
            Q(name__icontains=value) | Q(serial__icontains=value.strip())
            | Q(inventory_items__serial__icontains=value.strip())
            | Q(asset_tag__icontains=value.strip())
            | Q(comments__icontains=value)).distinct()

    def filter_region(self, queryset, name, value):
        try:
            region = Region.objects.get(**{name: value})
        except ObjectDoesNotExist:
            return queryset.none()
        return queryset.filter(
            Q(site__region=region)
            | Q(site__region__in=region.get_descendants()))

    def _mac_address(self, queryset, name, value):
        value = value.strip()
        if not value:
            return queryset
        try:
            mac = EUI(value.strip())
            return queryset.filter(interfaces__mac_address=mac).distinct()
        except AddrFormatError:
            return queryset.none()

    def _has_primary_ip(self, queryset, name, value):
        if value:
            return queryset.filter(
                Q(primary_ip4__isnull=False) | Q(primary_ip6__isnull=False))
        else:
            return queryset.exclude(
                Q(primary_ip4__isnull=False) | Q(primary_ip6__isnull=False))

    def _console_ports(self, queryset, name, value):
        return queryset.exclude(consoleports__isnull=value)

    def _console_server_ports(self, queryset, name, value):
        return queryset.exclude(consoleserverports__isnull=value)

    def _power_ports(self, queryset, name, value):
        return queryset.exclude(powerports__isnull=value)

    def _power_outlets(self, queryset, name, value):
        return queryset.exclude(poweroutlets_isnull=value)

    def _interfaces(self, queryset, name, value):
        return queryset.exclude(interfaces__isnull=value)

    def _pass_through_ports(self, queryset, name, value):
        return queryset.exclude(frontports__isnull=value,
                                rearports__isnull=value)
Exemple #5
0
class IPAddressFilter(CustomFieldFilterSet, django_filters.FilterSet):
    id__in = NumericInFilter(name='id', lookup_expr='in')
    q = django_filters.CharFilter(
        method='search',
        label='Search',
    )
    parent = django_filters.CharFilter(
        method='search_by_parent',
        label='Parent prefix',
    )
    mask_length = django_filters.NumberFilter(
        method='filter_mask_length',
        label='Mask length',
    )
    vrf_id = django_filters.ModelMultipleChoiceFilter(
        queryset=VRF.objects.all(),
        label='VRF',
    )
    vrf = django_filters.ModelMultipleChoiceFilter(
        name='vrf__rd',
        queryset=VRF.objects.all(),
        to_field_name='rd',
        label='VRF (RD)',
    )
    tenant_id = django_filters.ModelMultipleChoiceFilter(
        queryset=Tenant.objects.all(),
        label='Tenant (ID)',
    )
    tenant = django_filters.ModelMultipleChoiceFilter(
        name='tenant__slug',
        queryset=Tenant.objects.all(),
        to_field_name='slug',
        label='Tenant (slug)',
    )
    device_id = django_filters.ModelMultipleChoiceFilter(
        name='interface__device',
        queryset=Device.objects.all(),
        label='Device (ID)',
    )
    device = django_filters.ModelMultipleChoiceFilter(
        name='interface__device__name',
        queryset=Device.objects.all(),
        to_field_name='name',
        label='Device (name)',
    )
    virtual_machine_id = django_filters.ModelMultipleChoiceFilter(
        name='interface__virtual_machine',
        queryset=VirtualMachine.objects.all(),
        label='Virtual machine (ID)',
    )
    virtual_machine = django_filters.ModelMultipleChoiceFilter(
        name='interface__virtual_machine__name',
        queryset=VirtualMachine.objects.all(),
        to_field_name='name',
        label='Virtual machine (name)',
    )
    interface_id = django_filters.ModelMultipleChoiceFilter(
        queryset=Interface.objects.all(),
        label='Interface (ID)',
    )
    status = django_filters.MultipleChoiceFilter(
        choices=IPADDRESS_STATUS_CHOICES, null_value=None)
    role = django_filters.MultipleChoiceFilter(choices=IPADDRESS_ROLE_CHOICES)

    class Meta:
        model = IPAddress
        fields = ['family']

    def search(self, queryset, name, value):
        if not value.strip():
            return queryset
        qs_filter = (Q(description__icontains=value)
                     | Q(address__istartswith=value))
        return queryset.filter(qs_filter)

    def search_by_parent(self, queryset, name, value):
        value = value.strip()
        if not value:
            return queryset
        try:
            query = str(IPNetwork(value.strip()).cidr)
            return queryset.filter(address__net_host_contained=query)
        except (AddrFormatError, ValueError):
            return queryset.none()

    def filter_mask_length(self, queryset, name, value):
        if not value:
            return queryset
        return queryset.filter(address__net_mask_length=value)
Exemple #6
0
class DMAFilter(django_filters.FilterSet):
    project = django_filters.NumberFilter(field_name='project')
    fiscal_year = django_filters.NumberFilter(field_name='fiscal_year')
    title_name = django_filters.CharFilter(field_name='title',
                                           lookup_expr="icontains")
Exemple #7
0
class ProfileCustomFilter(filters.FilterSet):
    """
      We add custom filtering to allow you to filter by:

      * Profile ids  - pass the `?ids=` query parameter
      * Profile type - pass the `?profile_type=` query parameter
      * Program type - pass the `?program_type=` query parameter
      * Program year - pass the `?program_year=` query parameter
      * Limit results - pass the `?limit=` query parameter
    """
    ids = NumberInFilter(field_name='id', lookup_expr='in')
    profile_type = django_filters.CharFilter(
        name='profile_type__value',
        lookup_expr='iexact',
    )
    program_type = django_filters.CharFilter(
        name='program_type__value',
        lookup_expr='iexact',
    )
    program_year = django_filters.CharFilter(
        name='program_year__value',
        lookup_expr='iexact',
    )
    name = django_filters.CharFilter(method='filter_name')

    def filter_name(self, queryset, name, value):
        startswith_lookup = Q(custom_name__istartswith=value) | Q(
            related_user__name__istartswith=value)
        qs_startswith = queryset.filter(startswith_lookup)
        qs_contains = queryset.filter(
            Q(custom_name__icontains=value)
            | Q(related_user__name__icontains=value)).exclude(
                startswith_lookup)
        return list(chain(qs_startswith, qs_contains))

    limit = django_filters.NumberFilter(method='filter_limit')

    def filter_limit(self, queryset, name, value):
        return queryset.limit(value)

    @property
    def qs(self):
        """
        Ensure that if the filter route is called without
        a legal filtering argument, we return an empty
        queryset, rather than every profile in existence.
        """

        request = self.request
        if request is None:
            return UserProfile.objects.none()

        queries = self.request.query_params
        if queries is None:
            return UserProfile.objects.none()

        if 'search' in queries:
            qs = super(ProfileCustomFilter, self).qs
        else:
            qs = UserProfile.objects.none()

        fields = ProfileCustomFilter.get_fields()
        for key in fields:
            if key in queries:
                qs = super(ProfileCustomFilter, self).qs

        return qs

    class Meta:
        """
        Required Meta class
        """
        model = UserProfile
        fields = [
            'ids', 'profile_type', 'program_type', 'program_year', 'is_active',
            'name', 'limit'
        ]
Exemple #8
0
class IPAddressFilterSet(NautobotFilterSet, IPAMFilterSetMixin,
                         TenancyFilterSet, StatusModelFilterSetMixin):
    parent = django_filters.CharFilter(
        method="search_by_parent",
        label="Parent prefix",
    )
    address = MultiValueCharFilter(
        method="filter_address",
        label="Address",
    )
    mask_length = django_filters.NumberFilter(
        method="filter_mask_length",
        label="Mask length",
    )
    vrf_id = django_filters.ModelMultipleChoiceFilter(
        queryset=VRF.objects.all(),
        label="VRF",
    )
    vrf = django_filters.ModelMultipleChoiceFilter(
        field_name="vrf__rd",
        queryset=VRF.objects.all(),
        to_field_name="rd",
        label="VRF (RD)",
    )
    present_in_vrf_id = django_filters.ModelChoiceFilter(
        field_name="vrf",
        queryset=VRF.objects.all(),
        method="filter_present_in_vrf",
        label="VRF",
    )
    present_in_vrf = django_filters.ModelChoiceFilter(
        field_name="vrf__rd",
        queryset=VRF.objects.all(),
        method="filter_present_in_vrf",
        to_field_name="rd",
        label="VRF (RD)",
    )
    device = MultiValueCharFilter(
        method="filter_device",
        field_name="name",
        label="Device (name)",
    )
    device_id = MultiValueUUIDFilter(
        method="filter_device",
        field_name="pk",
        label="Device (ID)",
    )
    virtual_machine = MultiValueCharFilter(
        method="filter_virtual_machine",
        field_name="name",
        label="Virtual machine (name)",
    )
    virtual_machine_id = MultiValueUUIDFilter(
        method="filter_virtual_machine",
        field_name="pk",
        label="Virtual machine (ID)",
    )
    interface = django_filters.ModelMultipleChoiceFilter(
        field_name="interface__name",
        queryset=Interface.objects.all(),
        to_field_name="name",
        label="Interface (name)",
    )
    interface_id = django_filters.ModelMultipleChoiceFilter(
        field_name="interface",
        queryset=Interface.objects.all(),
        label="Interface (ID)",
    )
    vminterface = django_filters.ModelMultipleChoiceFilter(
        field_name="vminterface__name",
        queryset=VMInterface.objects.all(),
        to_field_name="name",
        label="VM interface (name)",
    )
    vminterface_id = django_filters.ModelMultipleChoiceFilter(
        field_name="vminterface",
        queryset=VMInterface.objects.all(),
        label="VM interface (ID)",
    )
    assigned_to_interface = django_filters.BooleanFilter(
        method="_assigned_to_interface",
        label="Is assigned to an interface",
    )
    role = django_filters.MultipleChoiceFilter(choices=IPAddressRoleChoices)
    tag = TagFilter()

    class Meta:
        model = IPAddress
        fields = ["id", "dns_name"]

    def search_by_parent(self, queryset, name, value):
        value = value.strip()
        if not value:
            return queryset
        try:
            query = netaddr.IPNetwork(value.strip()).cidr
            return queryset.net_host_contained(query)
        except (AddrFormatError, ValueError):
            return queryset.none()

    def filter_address(self, queryset, name, value):
        try:
            return queryset.net_in(value)
        except ValidationError:
            return queryset.none()

    def filter_mask_length(self, queryset, name, value):
        if not value:
            return queryset
        return queryset.filter(prefix_length=value)

    def filter_present_in_vrf(self, queryset, name, value):
        if value is None:
            return queryset.none
        return queryset.filter(
            Q(vrf=value)
            | Q(vrf__export_targets__in=value.import_targets.all()))

    def filter_device(self, queryset, name, value):
        devices = Device.objects.filter(**{"{}__in".format(name): value})
        if not devices.exists():
            return queryset.none()
        interface_ids = []
        for device in devices:
            interface_ids.extend(
                device.vc_interfaces.values_list("id", flat=True))
        return queryset.filter(interface__in=interface_ids)

    def filter_virtual_machine(self, queryset, name, value):
        virtual_machines = VirtualMachine.objects.filter(
            **{"{}__in".format(name): value})
        if not virtual_machines.exists():
            return queryset.none()
        interface_ids = []
        for vm in virtual_machines:
            interface_ids.extend(vm.interfaces.values_list("id", flat=True))
        return queryset.filter(vminterface__in=interface_ids)

    def _assigned_to_interface(self, queryset, name, value):
        return queryset.exclude(assigned_object_id__isnull=value)
Exemple #9
0
class TransientFilter(django_filters.FilterSet):
    def __init__(self, *args, **kwargs):
        super(TransientFilter, self).__init__(*args, **kwargs)
        if self.data == {}:
            self.queryset = self.queryset.none()

    def cone_search_filter(self, queryset, name, value):
        #Don't run if not all value are entered.
        if '' in value or None in value:
            return queryset
        else:
            ra = float(value[0])
            dec = float(value[1])
            radius = float(value[2])
            unit = value[3]
            scale_factors = {"arcsec": 3600., "arcmin": 60.}
            if unit in scale_factors:
                radius /= scale_factors[unit]

            return queryset.extra(where=[
                "q3c_radial_query(ra, dec, {:.6f}, {:.6f}, {:.6f})".format(
                    ra, dec, radius)
            ])

    def sort_by_filter(self, queryset, name, value):
        print(value)
        if value == '' or value == None:
            return queryset
        else:
            return queryset.order_by(value)

    source_id = django_filters.NumberFilter(field_name="id", label="Source ID")

    d2d__gt = django_filters.RangeFilter(field_name='d2d_askap_centre',
                                         widget=MyRangeWidget(
                                             from_attrs={'placeholder': 'Min'},
                                             to_attrs={'placeholder': 'Max'}))
    ratio__gt = django_filters.RangeFilter(
        field_name='ratio',
        widget=MyRangeWidget(from_attrs={'placeholder': 'Min'},
                             to_attrs={'placeholder': 'Max'}))

    vs__gt = django_filters.RangeFilter(field_name='vs',
                                        widget=MyRangeWidget(
                                            from_attrs={'placeholder': 'Min'},
                                            to_attrs={'placeholder': 'Max'}))
    m__gt = django_filters.RangeFilter(field_name='m',
                                       widget=MyRangeWidget(
                                           from_attrs={'placeholder': 'Min'},
                                           to_attrs={'placeholder': 'Max'}),
                                       label="m")

    askap_iflux__gt = MyRangeFilter(
        field_name='askap_iflux',
        widget=MyRangeWidget(from_attrs={'placeholder': 'Min (mJy)'},
                             to_attrs={'placeholder': 'Max (mJy)'}),
        label="ASKAP Integrated Flux")
    catalog_iflux__gt = MyRangeFilter(
        field_name='catalog_iflux',
        widget=MyRangeWidget(from_attrs={'placeholder': 'Min (mJy)'},
                             to_attrs={'placeholder': 'Max (mJy)'}),
        label="Catalogue Integrated Flux")

    pipelinetag_choices = (
        ('Good', 'Good'),
        ('Created convolved source', 'Created convolved source'),
        ('Edge of ASKAP image', 'Edge of ASKAP image'),
        ('Extended source', 'Extended source'),
        ('Failed', 'Failed'),
        ('Inflated convolved flux error', 'Inflated convolved flux error'),
        ('Large island source', 'Large island source'),
        ('Likely artefact (bright source)', 'Likely artefact (bright source)'),
        ('Likely bright extended structure',
         'Likely bright extended structure'),
        ('Likely double', 'Likely double/multi source'),
    )

    pipelinetag = django_filters.ChoiceFilter(field_name='pipelinetag',
                                              choices=pipelinetag_choices)

    convolved_error_choices = (
        ('True', 'True'),
        ('False', 'False'),
    )

    inflated_convolved_flux = django_filters.ChoiceFilter(
        field_name='inflated_convolved_flux', choices=convolved_error_choices)

    try:
        users = list(User.objects.values())
    except:
        users = []

    users = [(i["username"], i["username"])
             for i in sorted(users, key=lambda users: users['username'])
             ] + [("N/A", "Unchecked")]

    checkedby = django_filters.ChoiceFilter(field_name='checkedby',
                                            choices=users)

    transient_type_choices = (
        ('Match', 'Match'),
        ('No askap match', 'No ASKAP match'),
        ('No catalog match', 'No catalogue match'),
    )

    transient_type = django_filters.MultipleChoiceFilter(
        choices=transient_type_choices, widget=forms.CheckboxSelectMultiple)

    survey_choices = (
        ('sumss', 'SUMSS'),
        ('nvss', 'NVSS'),
    )

    survey = django_filters.MultipleChoiceFilter(
        choices=survey_choices, widget=forms.CheckboxSelectMultiple)

    usertag_choices = (
        ('investigate', 'Investigate'),
        ('transient', 'Transient'),
        ('help', 'Help'),
        ('problem', 'Problem'),
        ('ignore', 'Ignore'),
    )

    usertag = django_filters.ChoiceFilter(field_name='usertag',
                                          choices=usertag_choices)

    userreason_choices = (
        ('askap artefact', 'ASKAP artefact'),
        ('bright source', 'Bright source'),
        ('catalogue artefact', 'Catalogue artefact'),
        ('convolved flux error', 'Convolved flux error'),
        ('edge of field', 'Edge of field'),
        ('extended', 'Extended'),
        ('is match', 'Is match'),
        ('investigate', 'Investigate'),
        ('multiple', 'Multiple'),
        ('non-detection', 'Non-detection'),
        ('not sure', 'Not sure'),
        ('src. ext. error', 'Source extraction error'),
        ('too noisy', 'Too noisy'),
    )

    userreason = django_filters.ChoiceFilter(field_name='userreason',
                                             choices=userreason_choices)

    ra__gt = django_filters.RangeFilter(
        field_name='ra',
        widget=MyRangeWidget(from_attrs={'placeholder': 'Min (deg)'},
                             to_attrs={'placeholder': 'Max (deg)'}),
        label="Right Ascension")
    dec__gt = django_filters.RangeFilter(
        field_name='dec',
        widget=MyRangeWidget(from_attrs={'placeholder': 'Min (deg)'},
                             to_attrs={'placeholder': 'Max (deg)'}),
        label="Declination")

    gal_l__gt = django_filters.RangeFilter(
        field_name='gal_l',
        widget=MyRangeWidget(from_attrs={'placeholder': 'Min (deg)'},
                             to_attrs={'placeholder': 'Max (deg)'}),
        label="Galactic l")
    gal_b__gt = django_filters.RangeFilter(
        field_name='gal_b',
        widget=MyRangeWidget(from_attrs={'placeholder': 'Min (deg)'},
                             to_attrs={'placeholder': 'Max (deg)'}),
        label="Galactic b")

    d2d_nn_askap_cat__gt = django_filters.RangeFilter(
        field_name='d2d_nn_askap_cat',
        widget=MyRangeWidget(from_attrs={'placeholder': 'Min (arcsec)'},
                             to_attrs={'placeholder': 'Max (arcsec)'}),
        label="Distance to nearest ASKAP neighbour.")

    cone_search = ConeSearchFilter(field_name='cone_search',
                                   widget=ConeSearchWidget(),
                                   method="cone_search_filter",
                                   label="Cone Search")

    sortby_choices = (
        ('', '---------'),
        ('ratio', 'Ratio (asc)'),
        ('-ratio', 'Ratio (desc)'),
        ('askap_iflux', 'ASKAP Int. Flux (asc)'),
        ('-askap_iflux', 'ASKAP Int. Flux (desc)'),
        ('catalog_iflux', 'Catalogue Int. Flux (asc)'),
        ('-catalog_iflux', 'Catalogue Int. Flux (desc)'),
    )

    sort_by = ConeSearchFilter(
        field_name='sort_by',
        widget=forms.widgets.Select(choices=sortby_choices),
        method="sort_by_filter",
        label="Sort By")

    class Meta:
        model = Crossmatches
        fields = []
Exemple #10
0
class ResourceFilterSet(django_filters.FilterSet):
    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user')
        super().__init__(*args, **kwargs)

    purpose = ParentCharFilter(field_name='purposes__id', lookup_expr='iexact')
    type = django_filters.Filter(field_name='type__id',
                                 lookup_expr='in',
                                 widget=django_filters.widgets.CSVWidget)
    people = django_filters.NumberFilter(field_name='people_capacity',
                                         lookup_expr='gte')
    need_manual_confirmation = django_filters.BooleanFilter(
        field_name='need_manual_confirmation', widget=DRFFilterBooleanWidget)
    is_favorite = django_filters.BooleanFilter(method='filter_is_favorite',
                                               widget=DRFFilterBooleanWidget)
    unit = django_filters.CharFilter(field_name='unit__id',
                                     lookup_expr='iexact')
    resource_group = django_filters.Filter(
        field_name='groups__identifier',
        lookup_expr='in',
        widget=django_filters.widgets.CSVWidget,
        distinct=True)
    equipment = django_filters.Filter(
        field_name='resource_equipment__equipment__id',
        lookup_expr='in',
        widget=django_filters.widgets.CSVWidget,
        distinct=True)
    available_between = django_filters.Filter(
        method='filter_available_between',
        widget=django_filters.widgets.CSVWidget)
    free_of_charge = django_filters.BooleanFilter(
        method='filter_free_of_charge', widget=DRFFilterBooleanWidget)
    municipality = django_filters.Filter(
        field_name='unit__municipality_id',
        lookup_expr='in',
        widget=django_filters.widgets.CSVWidget,
        distinct=True)
    order_by = ResourceOrderingFilter(fields=(
        ('name_fi', 'resource_name_fi'),
        ('name_en', 'resource_name_en'),
        ('name_sv', 'resource_name_sv'),
        ('unit__name_fi', 'unit_name_fi'),
        ('unit__name_en', 'unit_name_en'),
        ('unit__name_sv', 'unit_name_sv'),
        ('type__name_fi', 'type_name_fi'),
        ('type__name_en', 'type_name_en'),
        ('type__name_sv', 'type_name_sv'),
        ('people_capacity', 'people_capacity'),
        ('accessibility_priority', 'accessibility'),
    ), )

    def filter_is_favorite(self, queryset, name, value):
        if not self.user.is_authenticated:
            if value:
                return queryset.none()
            else:
                return queryset

        if value:
            return queryset.filter(favorited_by=self.user)
        else:
            return queryset.exclude(favorited_by=self.user)

    def filter_free_of_charge(self, queryset, name, value):
        qs = Q(min_price_per_hour__lte=0) | Q(min_price_per_hour__isnull=True)
        if value:
            return queryset.filter(qs)
        else:
            return queryset.exclude(qs)

    def _deserialize_datetime(self, value):
        try:
            return arrow.get(value).datetime
        except ParserError:
            raise exceptions.ParseError(
                "'%s' must be a timestamp in ISO 8601 format" % value)

    def filter_available_between(self, queryset, name, value):
        if len(value) < 2 or len(value) > 3:
            raise exceptions.ParseError(
                'available_between takes two or three comma-separated values.')

        available_start = self._deserialize_datetime(value[0])
        available_end = self._deserialize_datetime(value[1])

        if available_start.date() != available_end.date():
            raise exceptions.ParseError(
                'available_between timestamps must be on the same day.')
        overlapping_reservations = Reservation.objects.filter(
            resource__in=queryset,
            end__gt=available_start,
            begin__lt=available_end).current()

        if len(value) == 2:
            return self._filter_available_between_whole_range(
                queryset, overlapping_reservations, available_start,
                available_end)
        else:
            try:
                period = datetime.timedelta(minutes=int(value[2]))
            except ValueError:
                raise exceptions.ParseError(
                    'available_between period must be an integer.')
            return self._filter_available_between_with_period(
                queryset, overlapping_reservations, available_start,
                available_end, period)

    def _filter_available_between_whole_range(self, queryset, reservations,
                                              available_start, available_end):
        # exclude resources that have reservation(s) overlapping with the available_between range
        queryset = queryset.exclude(reservations__in=reservations)
        closed_resource_ids = {
            resource.id
            for resource in queryset if not self._is_resource_open(
                resource, available_start, available_end)
        }

        return queryset.exclude(id__in=closed_resource_ids)

    @staticmethod
    def _is_resource_open(resource, start, end):
        opening_hours = resource.get_opening_hours(start, end)
        if len(opening_hours) > 1:
            # range spans over multiple days, assume resources aren't open all night and skip the resource
            return False

        hours = next(iter(opening_hours.values()))[
            0]  # assume there is only one hours obj per day
        if not hours['opens'] and not hours['closes']:
            return False

        start_too_early = hours['opens'] and start < hours['opens']
        end_too_late = hours['closes'] and end > hours['closes']
        if start_too_early or end_too_late:
            return False

        return True

    def _filter_available_between_with_period(self, queryset, reservations,
                                              available_start, available_end,
                                              period):
        reservations = reservations.order_by('begin').select_related(
            'resource')

        reservations_by_resource = collections.defaultdict(list)
        for reservation in reservations:
            reservations_by_resource[reservation.resource_id].append(
                reservation)

        available_resources = set()

        hours_qs = ResourceDailyOpeningHours.objects.filter(
            open_between__overlap=(available_start, available_end, '[)'))

        # check the resources one by one to determine which ones have open slots
        for resource in queryset.prefetch_related(None).prefetch_related(
                Prefetch('opening_hours',
                         queryset=hours_qs,
                         to_attr='prefetched_opening_hours')):
            reservations = reservations_by_resource[resource.id]

            if self._is_resource_available(resource, available_start,
                                           available_end, reservations,
                                           period):
                available_resources.add(resource.id)

        return queryset.filter(id__in=available_resources)

    @staticmethod
    def _is_resource_available(resource, available_start, available_end,
                               reservations, period):
        opening_hours = resource.get_opening_hours(
            available_start, available_end, resource.prefetched_opening_hours)
        hours = next(iter(opening_hours.values()))[
            0]  # assume there is only one hours obj per day

        if not (hours['opens'] or hours['closes']):
            return False

        current = max(
            available_start,
            hours['opens']) if hours['opens'] is not None else available_start
        end = min(
            available_end,
            hours['closes']) if hours['closes'] is not None else available_end

        if current >= end:
            # the resource is already closed
            return False

        if not reservations:
            # the resource has no reservations, just check if the period fits in the resource's opening times
            if end - current >= period:
                return True
            return False

        # try to find an open slot between reservations and opening / closing times.
        # start from period start time or opening time depending on which one is earlier.
        for reservation in reservations:
            if reservation.end <= current:
                # this reservation is in the past
                continue
            if reservation.begin - current >= period:
                # found an open slot before the reservation currently being examined
                return True
            if reservation.end > end:
                # the reservation currently being examined ends after the period or closing time,
                # so no free slots
                return False
            # did not find an open slot before the reservation currently being examined,
            # proceed to next reservation
            current = reservation.end
        else:
            # all reservations checked and no free slot found, check if there is a free slot after the last
            # reservation
            if end - reservation.end >= period:
                return True

        return False

    class Meta:
        model = Resource
        fields = [
            'purpose', 'type', 'people', 'need_manual_confirmation',
            'is_favorite', 'unit', 'available_between', 'min_price_per_hour'
        ]
Exemple #11
0
class PrefixFilterSet(NautobotFilterSet, IPAMFilterSetMixin, TenancyFilterSet,
                      StatusModelFilterSetMixin):
    prefix = django_filters.CharFilter(
        method="filter_prefix",
        label="Prefix",
    )
    within = django_filters.CharFilter(
        method="search_within",
        label="Within prefix",
    )
    within_include = django_filters.CharFilter(
        method="search_within_include",
        label="Within and including prefix",
    )
    contains = django_filters.CharFilter(
        method="search_contains",
        label="Prefixes which contain this prefix or IP",
    )
    mask_length = django_filters.NumberFilter(label="mask_length",
                                              method="filter_prefix_length_eq")
    mask_length__gte = django_filters.NumberFilter(
        label="mask_length__gte", method="filter_prefix_length_gte")
    mask_length__lte = django_filters.NumberFilter(
        label="mask_length__lte", method="filter_prefix_length_lte")
    vrf_id = django_filters.ModelMultipleChoiceFilter(
        queryset=VRF.objects.all(),
        label="VRF",
    )
    vrf = django_filters.ModelMultipleChoiceFilter(
        field_name="vrf__rd",
        queryset=VRF.objects.all(),
        to_field_name="rd",
        label="VRF (RD)",
    )
    present_in_vrf_id = django_filters.ModelChoiceFilter(
        field_name="vrf",
        queryset=VRF.objects.all(),
        method="filter_present_in_vrf",
        label="VRF",
    )
    present_in_vrf = django_filters.ModelChoiceFilter(
        field_name="vrf__rd",
        queryset=VRF.objects.all(),
        method="filter_present_in_vrf",
        to_field_name="rd",
        label="VRF (RD)",
    )
    region_id = TreeNodeMultipleChoiceFilter(
        queryset=Region.objects.all(),
        field_name="site__region",
        lookup_expr="in",
        label="Region (ID)",
    )
    region = TreeNodeMultipleChoiceFilter(
        queryset=Region.objects.all(),
        field_name="site__region",
        lookup_expr="in",
        to_field_name="slug",
        label="Region (slug)",
    )
    site_id = django_filters.ModelMultipleChoiceFilter(
        queryset=Site.objects.all(),
        label="Site (ID)",
    )
    site = django_filters.ModelMultipleChoiceFilter(
        field_name="site__slug",
        queryset=Site.objects.all(),
        to_field_name="slug",
        label="Site (slug)",
    )
    vlan_id = django_filters.ModelMultipleChoiceFilter(
        queryset=VLAN.objects.all(),
        label="VLAN (ID)",
    )
    vlan_vid = django_filters.NumberFilter(
        field_name="vlan__vid",
        label="VLAN number (1-4095)",
    )
    role_id = django_filters.ModelMultipleChoiceFilter(
        queryset=Role.objects.all(),
        label="Role (ID)",
    )
    role = django_filters.ModelMultipleChoiceFilter(
        field_name="role__slug",
        queryset=Role.objects.all(),
        to_field_name="slug",
        label="Role (slug)",
    )
    tag = TagFilter()

    class Meta:
        model = Prefix
        fields = ["id", "is_pool", "prefix"]

    def filter_prefix(self, queryset, name, value):
        value = value.strip()
        if not value:
            return queryset
        # filter for Prefix models equal to |value|
        try:
            return queryset.net_equals(netaddr.IPNetwork(value))
        except (AddrFormatError, ValueError):
            return queryset.none()

    def filter_prefix_length_eq(self, queryset, name, value):
        return queryset.filter(prefix_length__exact=value)

    def filter_prefix_length_lte(self, queryset, name, value):
        return queryset.filter(prefix_length__lte=value)

    def filter_prefix_length_gte(self, queryset, name, value):
        return queryset.filter(prefix_length__gte=value)

    def search_within(self, queryset, name, value):
        value = value.strip()
        if not value:
            return queryset
        try:
            return queryset.net_contained(netaddr.IPNetwork(value))
        except (AddrFormatError, ValueError):
            return queryset.none()

    def search_within_include(self, queryset, name, value):
        value = value.strip()
        if not value:
            return queryset
        try:
            return queryset.net_contained_or_equal(netaddr.IPNetwork(value))
        except (AddrFormatError, ValueError):
            return queryset.none()

    def search_contains(self, queryset, name, value):
        value = value.strip()
        if not value:
            return queryset
        try:
            # Searching by prefix
            if "/" in value:
                return queryset.net_contains_or_equals(
                    netaddr.IPNetwork(value).cidr)
            # Searching by IP address
            else:
                # filter for Prefixes containing |value|
                # netaddr.IPAddress objects have no netmask
                # so prefix_length is not considered
                query = netaddr.IPAddress(value)
                return queryset.filter(
                    network__lte=bytes(query),
                    broadcast__gte=bytes(query),
                )
        except (AddrFormatError, ValueError):
            return queryset.none()

    def filter_present_in_vrf(self, queryset, name, value):
        if value is None:
            return queryset.none
        return queryset.filter(
            Q(vrf=value)
            | Q(vrf__export_targets__in=value.import_targets.all()))
Exemple #12
0
class PriceFilter(django_filters.FilterSet):
    category = django_filters.NumberFilter('category__id')
Exemple #13
0
class FlatDataFilterSet(django_filters.FilterSet):
    field_01_null = django_filters.BooleanFilter(field_name='field_01', lookup_expr='isnull')
    field_02_null = django_filters.BooleanFilter(field_name='field_02', lookup_expr='isnull')
    field_03_null = django_filters.BooleanFilter(field_name='field_03', lookup_expr='isnull')
    field_04_null = django_filters.BooleanFilter(field_name='field_04', lookup_expr='isnull')
    field_05_null = django_filters.BooleanFilter(field_name='field_05', lookup_expr='isnull')
    field_06_null = django_filters.BooleanFilter(field_name='field_06', lookup_expr='isnull')
    field_07_null = django_filters.BooleanFilter(field_name='field_07', lookup_expr='isnull')
    field_08_null = django_filters.BooleanFilter(field_name='field_08', lookup_expr='isnull')
    field_09_null = django_filters.BooleanFilter(field_name='field_09', lookup_expr='isnull')
    field_10_null = django_filters.BooleanFilter(field_name='field_10', lookup_expr='isnull')
    field_11_null = django_filters.BooleanFilter(field_name='field_11', lookup_expr='isnull')
    field_12_null = django_filters.BooleanFilter(field_name='field_12', lookup_expr='isnull')
    field_13_null = django_filters.BooleanFilter(field_name='field_13', lookup_expr='isnull')
    field_14_null = django_filters.BooleanFilter(field_name='field_14', lookup_expr='isnull')
    field_15_null = django_filters.BooleanFilter(field_name='field_15', lookup_expr='isnull')
    field_16_null = django_filters.BooleanFilter(field_name='field_16', lookup_expr='isnull')
    field_17_null = django_filters.BooleanFilter(field_name='field_17', lookup_expr='isnull')
    field_18_null = django_filters.BooleanFilter(field_name='field_18', lookup_expr='isnull')
    field_19_null = django_filters.BooleanFilter(field_name='field_19', lookup_expr='isnull')
    field_20_null = django_filters.BooleanFilter(field_name='field_20', lookup_expr='isnull')
    field_21_null = django_filters.BooleanFilter(field_name='field_21', lookup_expr='isnull')
    field_22_null = django_filters.BooleanFilter(field_name='field_22', lookup_expr='isnull')
    field_23_null = django_filters.BooleanFilter(field_name='field_23', lookup_expr='isnull')
    field_24_null = django_filters.BooleanFilter(field_name='field_24', lookup_expr='isnull')
    field_25_null = django_filters.BooleanFilter(field_name='field_25', lookup_expr='isnull')
    field_26_null = django_filters.BooleanFilter(field_name='field_26', lookup_expr='isnull')
    field_27_null = django_filters.BooleanFilter(field_name='field_27', lookup_expr='isnull')
    field_28_null = django_filters.BooleanFilter(field_name='field_28', lookup_expr='isnull')
    field_29_null = django_filters.BooleanFilter(field_name='field_29', lookup_expr='isnull')
    field_30_null = django_filters.BooleanFilter(field_name='field_30', lookup_expr='isnull')

    field_01_not = django_filters.CharFilter(field_name='field_01', exclude=True)
    field_02_not = django_filters.CharFilter(field_name='field_02', exclude=True)
    field_03_not = django_filters.CharFilter(field_name='field_03', exclude=True)
    field_04_not = django_filters.CharFilter(field_name='field_04', exclude=True)
    field_05_not = django_filters.CharFilter(field_name='field_05', exclude=True)
    field_06_not = django_filters.CharFilter(field_name='field_06', exclude=True)
    field_07_not = django_filters.CharFilter(field_name='field_07', exclude=True)
    field_08_not = django_filters.CharFilter(field_name='field_08', exclude=True)
    field_09_not = django_filters.CharFilter(field_name='field_09', exclude=True)
    field_10_not = django_filters.CharFilter(field_name='field_10', exclude=True)
    field_11_not = django_filters.CharFilter(field_name='field_11', exclude=True)
    field_12_not = django_filters.CharFilter(field_name='field_12', exclude=True)
    field_13_not = django_filters.CharFilter(field_name='field_13', exclude=True)
    field_14_not = django_filters.CharFilter(field_name='field_14', exclude=True)
    field_15_not = django_filters.CharFilter(field_name='field_15', exclude=True)
    field_16_not = django_filters.CharFilter(field_name='field_16', exclude=True)
    field_17_not = django_filters.CharFilter(field_name='field_17', exclude=True)
    field_18_not = django_filters.CharFilter(field_name='field_18', exclude=True)
    field_19_not = django_filters.CharFilter(field_name='field_19', exclude=True)
    field_20_not = django_filters.CharFilter(field_name='field_20', exclude=True)
    field_21_not = django_filters.CharFilter(field_name='field_21', exclude=True)
    field_22_not = django_filters.CharFilter(field_name='field_22', exclude=True)
    field_23_not = django_filters.CharFilter(field_name='field_23', exclude=True)
    field_24_not = django_filters.CharFilter(field_name='field_24', exclude=True)
    field_25_not = django_filters.CharFilter(field_name='field_25', exclude=True)
    field_26_not = django_filters.CharFilter(field_name='field_26', exclude=True)
    field_27_not = django_filters.CharFilter(field_name='field_27', exclude=True)
    field_28_not = django_filters.CharFilter(field_name='field_28', exclude=True)
    field_29_not = django_filters.CharFilter(field_name='field_29', exclude=True)
    field_30_not = django_filters.CharFilter(field_name='field_30', exclude=True)

    field_01_in = CharInFilter(field_name='field_01', lookup_expr='in')
    field_02_in = CharInFilter(field_name='field_02', lookup_expr='in')
    field_03_in = CharInFilter(field_name='field_03', lookup_expr='in')
    field_04_in = CharInFilter(field_name='field_04', lookup_expr='in')
    field_05_in = CharInFilter(field_name='field_05', lookup_expr='in')
    field_06_in = CharInFilter(field_name='field_06', lookup_expr='in')
    field_07_in = CharInFilter(field_name='field_07', lookup_expr='in')
    field_08_in = CharInFilter(field_name='field_08', lookup_expr='in')
    field_09_in = CharInFilter(field_name='field_09', lookup_expr='in')
    field_10_in = CharInFilter(field_name='field_10', lookup_expr='in')
    field_11_in = CharInFilter(field_name='field_11', lookup_expr='in')
    field_12_in = CharInFilter(field_name='field_12', lookup_expr='in')
    field_13_in = CharInFilter(field_name='field_13', lookup_expr='in')
    field_14_in = CharInFilter(field_name='field_14', lookup_expr='in')
    field_15_in = CharInFilter(field_name='field_15', lookup_expr='in')
    field_16_in = CharInFilter(field_name='field_16', lookup_expr='in')
    field_17_in = CharInFilter(field_name='field_17', lookup_expr='in')
    field_18_in = CharInFilter(field_name='field_18', lookup_expr='in')
    field_19_in = CharInFilter(field_name='field_19', lookup_expr='in')
    field_20_in = CharInFilter(field_name='field_20', lookup_expr='in')
    field_21_in = CharInFilter(field_name='field_21', lookup_expr='in')
    field_22_in = CharInFilter(field_name='field_22', lookup_expr='in')
    field_23_in = CharInFilter(field_name='field_23', lookup_expr='in')
    field_24_in = CharInFilter(field_name='field_24', lookup_expr='in')
    field_25_in = CharInFilter(field_name='field_25', lookup_expr='in')
    field_26_in = CharInFilter(field_name='field_26', lookup_expr='in')
    field_27_in = CharInFilter(field_name='field_27', lookup_expr='in')
    field_28_in = CharInFilter(field_name='field_28', lookup_expr='in')
    field_29_in = CharInFilter(field_name='field_29', lookup_expr='in')
    field_30_in = CharInFilter(field_name='field_30', lookup_expr='in')

    date_01_year = django_filters.NumberFilter(field_name='date_01', lookup_expr='year')
    date_02_year = django_filters.NumberFilter(field_name='date_02', lookup_expr='year')
    date_03_year = django_filters.NumberFilter(field_name='date_03', lookup_expr='year')
    date_04_year = django_filters.NumberFilter(field_name='date_04', lookup_expr='year')
    date_05_year = django_filters.NumberFilter(field_name='date_05', lookup_expr='year')
    date_06_year = django_filters.NumberFilter(field_name='date_06', lookup_expr='year')
    date_07_year = django_filters.NumberFilter(field_name='date_07', lookup_expr='year')
    date_08_year = django_filters.NumberFilter(field_name='date_08', lookup_expr='year')
    date_09_year = django_filters.NumberFilter(field_name='date_09', lookup_expr='year')
    date_10_year = django_filters.NumberFilter(field_name='date_10', lookup_expr='year')

    date_01_month = django_filters.NumberFilter(field_name='date_01', lookup_expr='month')
    date_02_month = django_filters.NumberFilter(field_name='date_02', lookup_expr='month')
    date_03_month = django_filters.NumberFilter(field_name='date_03', lookup_expr='month')
    date_04_month = django_filters.NumberFilter(field_name='date_04', lookup_expr='month')
    date_05_month = django_filters.NumberFilter(field_name='date_05', lookup_expr='month')
    date_06_month = django_filters.NumberFilter(field_name='date_06', lookup_expr='month')
    date_07_month = django_filters.NumberFilter(field_name='date_07', lookup_expr='month')
    date_08_month = django_filters.NumberFilter(field_name='date_08', lookup_expr='month')
    date_09_month = django_filters.NumberFilter(field_name='date_09', lookup_expr='month')
    date_10_month = django_filters.NumberFilter(field_name='date_10', lookup_expr='month')

    date_01_day = django_filters.NumberFilter(field_name='date_01', lookup_expr='day')
    date_02_day = django_filters.NumberFilter(field_name='date_02', lookup_expr='day')
    date_03_day = django_filters.NumberFilter(field_name='date_03', lookup_expr='day')
    date_04_day = django_filters.NumberFilter(field_name='date_04', lookup_expr='day')
    date_05_day = django_filters.NumberFilter(field_name='date_05', lookup_expr='day')
    date_06_day = django_filters.NumberFilter(field_name='date_06', lookup_expr='day')
    date_07_day = django_filters.NumberFilter(field_name='date_07', lookup_expr='day')
    date_08_day = django_filters.NumberFilter(field_name='date_08', lookup_expr='day')
    date_09_day = django_filters.NumberFilter(field_name='date_09', lookup_expr='day')
    date_10_day = django_filters.NumberFilter(field_name='date_10', lookup_expr='day')

    datetime_01_year = django_filters.NumberFilter(field_name='datetime_01', lookup_expr='year')
    datetime_02_year = django_filters.NumberFilter(field_name='datetime_02', lookup_expr='year')
    datetime_03_year = django_filters.NumberFilter(field_name='datetime_03', lookup_expr='year')
    datetime_04_year = django_filters.NumberFilter(field_name='datetime_04', lookup_expr='year')
    datetime_05_year = django_filters.NumberFilter(field_name='datetime_05', lookup_expr='year')
    datetime_06_year = django_filters.NumberFilter(field_name='datetime_06', lookup_expr='year')
    datetime_07_year = django_filters.NumberFilter(field_name='datetime_07', lookup_expr='year')
    datetime_08_year = django_filters.NumberFilter(field_name='datetime_08', lookup_expr='year')
    datetime_09_year = django_filters.NumberFilter(field_name='datetime_09', lookup_expr='year')
    datetime_10_year = django_filters.NumberFilter(field_name='datetime_10', lookup_expr='year')

    datetime_01_month = django_filters.NumberFilter(field_name='datetime_01', lookup_expr='month')
    datetime_02_month = django_filters.NumberFilter(field_name='datetime_02', lookup_expr='month')
    datetime_03_month = django_filters.NumberFilter(field_name='datetime_03', lookup_expr='month')
    datetime_04_month = django_filters.NumberFilter(field_name='datetime_04', lookup_expr='month')
    datetime_05_month = django_filters.NumberFilter(field_name='datetime_05', lookup_expr='month')
    datetime_06_month = django_filters.NumberFilter(field_name='datetime_06', lookup_expr='month')
    datetime_07_month = django_filters.NumberFilter(field_name='datetime_07', lookup_expr='month')
    datetime_08_month = django_filters.NumberFilter(field_name='datetime_08', lookup_expr='month')
    datetime_09_month = django_filters.NumberFilter(field_name='datetime_09', lookup_expr='month')
    datetime_10_month = django_filters.NumberFilter(field_name='datetime_10', lookup_expr='month')

    datetime_01_day = django_filters.NumberFilter(field_name='datetime_01', lookup_expr='day')
    datetime_02_day = django_filters.NumberFilter(field_name='datetime_02', lookup_expr='day')
    datetime_03_day = django_filters.NumberFilter(field_name='datetime_03', lookup_expr='day')
    datetime_04_day = django_filters.NumberFilter(field_name='datetime_04', lookup_expr='day')
    datetime_05_day = django_filters.NumberFilter(field_name='datetime_05', lookup_expr='day')
    datetime_06_day = django_filters.NumberFilter(field_name='datetime_06', lookup_expr='day')
    datetime_07_day = django_filters.NumberFilter(field_name='datetime_07', lookup_expr='day')
    datetime_08_day = django_filters.NumberFilter(field_name='datetime_08', lookup_expr='day')
    datetime_09_day = django_filters.NumberFilter(field_name='datetime_09', lookup_expr='day')
    datetime_10_day = django_filters.NumberFilter(field_name='datetime_10', lookup_expr='day')

    int_01_range = django_filters.RangeFilter(field_name='int_01', help_text='int_xx_range_min=xx&int_xx_range_max=xx')
    int_02_range = django_filters.RangeFilter(field_name='int_02', help_text='int_xx_range_min=xx&int_xx_range_max=xx')
    int_03_range = django_filters.RangeFilter(field_name='int_03', help_text='int_xx_range_min=xx&int_xx_range_max=xx')
    int_04_range = django_filters.RangeFilter(field_name='int_04', help_text='int_xx_range_min=xx&int_xx_range_max=xx')
    int_05_range = django_filters.RangeFilter(field_name='int_05', help_text='int_xx_range_min=xx&int_xx_range_max=xx')
    int_06_range = django_filters.RangeFilter(field_name='int_06', help_text='int_xx_range_min=xx&int_xx_range_max=xx')
    int_07_range = django_filters.RangeFilter(field_name='int_07', help_text='int_xx_range_min=xx&int_xx_range_max=xx')
    int_08_range = django_filters.RangeFilter(field_name='int_08', help_text='int_xx_range_min=xx&int_xx_range_max=xx')
    int_09_range = django_filters.RangeFilter(field_name='int_09', help_text='int_xx_range_min=xx&int_xx_range_max=xx')
    int_10_range = django_filters.RangeFilter(field_name='int_10', help_text='int_xx_range_min=xx&int_xx_range_max=xx')
    float_01_range = django_filters.RangeFilter(field_name='float_01', help_text='')
    float_02_range = django_filters.RangeFilter(field_name='float_02', help_text='')
    float_03_range = django_filters.RangeFilter(field_name='float_03', help_text='')
    float_04_range = django_filters.RangeFilter(field_name='float_04', help_text='')
    float_05_range = django_filters.RangeFilter(field_name='float_05', help_text='')
    float_06_range = django_filters.RangeFilter(field_name='float_06', help_text='')
    float_07_range = django_filters.RangeFilter(field_name='float_07', help_text='')
    float_08_range = django_filters.RangeFilter(field_name='float_08', help_text='')
    float_09_range = django_filters.RangeFilter(field_name='float_09', help_text='')
    float_10_range = django_filters.RangeFilter(field_name='float_10', help_text='')

    class Meta:
        model = models.FlatData
        fields = (
            'sys_id',
            'org_id',
            'biz_id',
            'field_01',
            'field_02',
            'field_03',
            'field_04',
            'field_05',
            'field_06',
            'field_07',
            'field_08',
            'field_09',
            'field_10',
            'field_11',
            'field_12',
            'field_13',
            'field_14',
            'field_15',
            'field_16',
            'field_17',
            'field_18',
            'field_19',
            'field_20',
            'field_21',
            'field_22',
            'field_23',
            'field_24',
            'field_25',
            'field_26',
            'field_27',
            'field_28',
            'field_29',
            'field_30',
            'date_01',
            'date_02',
            'date_03',
            'date_04',
            'date_05',
            'date_06',
            'date_07',
            'date_08',
            'date_09',
            'date_10',
            'datetime_01',
            'datetime_02',
            'datetime_03',
            'datetime_04',
            'datetime_05',
            'datetime_06',
            'datetime_07',
            'datetime_08',
            'datetime_09',
            'datetime_10',
            'int_01',
            'int_02',
            'int_03',
            'int_04',
            'int_05',
            'int_06',
            'int_07',
            'int_08',
            'int_09',
            'int_10',
            'float_01',
            'float_02',
            'float_03',
            'float_04',
            'float_05',
            'float_06',
            'float_07',
            'float_08',
            'float_09',
            'float_10',
        )
Exemple #14
0
class PersonFilter(django_filters.FilterSet):
    SchoolAttend = django_filters.ModelChoiceFilter(
        name='persontoschool__SchoolID',
        queryset=School.objects.all().order_by('Name'),
        to_field_name='id')
    #SchoolAttend = django_filters.ModelChoiceFilter(name='school__Name',
    #queryset=School.objects.values_list('Name',flat=True),
    #to_field_name='Name', lookup_expr='icontains', widget=forms.TextInput)
    GraduateDate = django_filters.ModelChoiceFilter(
        name='persontoschool__GradDate',
        queryset=PersonToSchool.objects.values_list(
            'GradDate', flat=True).distinct().order_by('GradDate'),
        to_field_name='GradDate')
    Major = django_filters.ModelChoiceFilter(
        name='persontoschool__MajorID',
        queryset=Major.objects.all().order_by('Name'))
    DegreeLevel = django_filters.ModelChoiceFilter(
        name='school__DegreeLevel',
        queryset=School.objects.values_list('DegreeLevel',
                                            flat=True).distinct(),
        to_field_name='DegreeLevel')
    #GPA = django_filters.ModelChoiceFilter(name='persontoschool__GPA',
    #                                                queryset=PersonToSchool.objects.values_list('GPA',flat=True).distinct(),
    #                                                to_field_name='GPA', lookup_expr='gte',
    #                                       widget=RangeWidget(attrs={'placeholder': '0.0'}))
    GPAlb = django_filters.NumberFilter(name='persontoschool__GPA',
                                        lookup_expr='gte')
    GPAub = django_filters.NumberFilter(name='persontoschool__GPA',
                                        lookup_expr='lt')
    Language = django_filters.ModelChoiceFilter(
        name='persontolanguage__LangID',
        queryset=LanguageSpoken.objects.all().order_by('Language'))
    Skills = django_filters.ModelChoiceFilter(
        name='persontoskills__SkillsID',
        queryset=Skills.objects.all().order_by('Name').distinct())
    YearOfExperienceForSkill = django_filters.ModelChoiceFilter(
        name='persontoskills__YearsOfExperience',
        queryset=PersonToSkills.objects.values_list(
            'YearsOfExperience',
            flat=True).distinct().order_by('YearsOfExperience'),
        to_field_name='YearsOfExperience')
    #ProfessionalDevelopment = django_filters.ModelChoiceFilter(name='persontoprofessionaldevelopment__ProfID',
    #                                                           queryset=ProfessionalDevelopment.objects.all().order_by('Name'))
    #ProfessionalDevelopment = django_filters.ModelChoiceFilter(name='professionaldevelopment__Name',
    #                                                           queryset=ProfessionalDevelopment.objects.values_list('Name', flat=True),
    #                                                          to_field_name='Name', lookup_expr='icontains',
    #                                                          widget=forms.TextInput)
    ProfessionalDevelopment = django_filters.CharFilter(
        name='professionaldevelopment__Name', lookup_expr='icontains')
    Award = django_filters.ModelChoiceFilter(
        name='persontoawards__AwardID',
        queryset=Awards.objects.all().order_by('Name'))
    CompanyWorked = django_filters.ModelChoiceFilter(
        name='persontocompany__CompanyID',
        queryset=Company.objects.all().order_by('Name'))
    Title = django_filters.ModelChoiceFilter(
        name='persontocompany__Title',
        queryset=PersonToCompany.objects.values_list(
            'Title', flat=True).distinct().order_by('Title'),
        to_field_name='Title')
    Volunteering = django_filters.CharFilter(name='volunteering__Name',
                                             lookup_expr='icontains')
    Club_Hobby = django_filters.ModelChoiceFilter(
        name='persontoclubshobbies_set__CHID',
        queryset=Clubs_Hobbies.objects.all().distinct().order_by('Name'))
    SecurityClearance = django_filters.ModelChoiceFilter(
        name='persontoclearance__ClearanceLevel',
        queryset=Clearance.objects.all().order_by('ClearanceLevel'))

    class Meta:
        model = Person
        fields = [
            'SchoolAttend', 'GraduateDate', 'Major', 'DegreeLevel', 'GPAlb',
            'GPAub', 'Language', 'Skills', 'YearOfExperienceForSkill',
            'ProfessionalDevelopment', 'Award', 'CompanyWorked', 'Title',
            'SecurityClearance', 'Volunteering', 'Club_Hobby'
        ]
Exemple #15
0
class SpeakerFilter(django_filters.FilterSet):
    summit_id = django_filters.NumberFilter(
        method='has_events_from_summit_filter')
    published_in = django_filters.NumberFilter(
        method='has_published_events_from_summit_filter')
    search = django_filters.CharFilter(method='search_filter')
    has_feedback_for_summit = django_filters.NumberFilter(
        method='feedback_filter')
    track = django_filters.BaseInFilter(
        field_name='presentations__category__id')
    confirmed_for_summit = django_filters.CharFilter(method='confirmed_filter')
    checkedin_for_summit = django_filters.CharFilter(method='checked_filter')
    registered_for_summit = django_filters.CharFilter(
        method='registered_filter')
    attending_media_for_summit = django_filters.CharFilter(
        method='attending_media_filter')

    class Meta:
        model = Speaker
        fields = ['id', 'first_name', 'last_name']

    def has_events_from_summit_filter(self, queryset, name, value):
        return queryset.filter(presentations__summit__id=value).distinct()

    def has_published_events_from_summit_filter(self, queryset, name, value):
        return queryset.filter(presentations__summit__id=value,
                               presentations__published=True).distinct()

    def has_events_on_category_filter(self, queryset, name, value):
        return queryset.filter(presentations__category__id=value).distinct()

    def confirmed_filter(self, queryset, name, value):
        values = value.split(',')
        summit_id = values[0]
        confirmed = values[1] == 'true'
        return queryset.filter(attendances__summit__id=summit_id,
                               attendances__confirmed=confirmed).distinct()

    def registered_filter(self, queryset, name, value):
        values = value.split(',')
        summit_id = values[0]
        registered = values[1] == 'true'
        return queryset.filter(attendances__summit__id=summit_id,
                               attendances__registered=registered).distinct()

    def checked_filter(self, queryset, name, value):
        values = value.split(',')
        summit_id = values[0]
        checked = values[1] == 'true'
        return queryset.filter(attendances__summit__id=summit_id,
                               attendances__checked_in=checked).distinct()

    def attending_media_filter(self, queryset, name, value):
        values = value.split(',')
        summit_id = values[0]
        attending = values[1] == 'true'
        return queryset.filter(
            presentations__summit__id=summit_id,
            presentations__attending_media=attending).distinct()

    def search_filter(self, queryset, name, value):
        queryset = queryset.filter(
            models.Q(last_name=value) | models.Q(member__email=value)
            | models.Q(presentations__title__icontains=value))
        return queryset.distinct()

    def feedback_filter(self, queryset, name, value):
        feedbacks = EventFeedback.objects.filter(
            event__presentation__speakers=models.OuterRef('id'),
            event__summit__id=value)

        queryTmp = queryset.annotate(
            has_feedback=models.Exists(feedbacks)).filter(has_feedback=True)
        queryTmp = queryTmp.annotate(rate=SubQueryAvg(feedbacks, field="rate"))

        return queryTmp
Exemple #16
0
class TitleFilter(django_filters.FilterSet):
    name = django_filters.CharFilter(field_name='name',
                                     lookup_expr='icontains')
    genre = django_filters.CharFilter(field_name='genre__slug')
    category = django_filters.CharFilter(field_name='category__slug')
    year = django_filters.NumberFilter(field_name='year')
Exemple #17
0
class RsvpTemplateFilter(django_filters.FilterSet):
    event_id = django_filters.NumberFilter(field_name='event__id')

    class Meta:
        model = RsvpTemplate
        fields = ['id', 'title', 'questions']
Exemple #18
0
class VoterFilter(django_filters.FilterSet):
    birth_age_gt = django_filters.NumberFilter(
        name='birth_age',
        label='Age greater than',
        lookup_expr='gt',
    )
    birth_age_lt = django_filters.NumberFilter(
        name='birth_age',
        label='and less than',
        lookup_expr='lt',
    )
    birth_state = django_filters.MultipleChoiceFilter(
        name='birth_state',
        label='Birth state',
        choices=Voter.STATE_CHOICES,
    )
    gender_code = django_filters.MultipleChoiceFilter(
        name='gender_code',
        label='Gender',
        choices=Voter.GENDER_CHOICES,
    )
    race_code = django_filters.MultipleChoiceFilter(name='race_code',
                                                    label='Race',
                                                    choices=Voter.RACE_CHOICES,
                                                    null_label='(blank)')
    ethnic_code = django_filters.ChoiceFilter(
        name='ethnic_code',
        label='Ethnicity',
        choices=Voter.ETHNIC_CHOICES,
    )
    registr_dt_gt = django_filters.DateFilter(
        name='registr_dt',
        label='Registered after',
        lookup_expr='gt',
    )
    registr_dt_lt = django_filters.DateFilter(
        name='registr_dt',
        label='and before',
        lookup_expr='lt',
    )
    party_cd = django_filters.MultipleChoiceFilter(
        name='party_cd',
        label='Registered party',
        choices=Voter.PARTY_CHOICES,
    )
    county = django_filters.ModelMultipleChoiceFilter(
        name='county',
        label='County',
        queryset=County.objects.all(),
    )
    congressional = django_filters.ModelMultipleChoiceFilter(
        name='congressional',
        label='Congressional District',
        queryset=CongressionalDistrict.objects.exclude(abbrv=''),
    )
    state_senate = django_filters.ModelMultipleChoiceFilter(
        name='state_senate',
        label='State Senate District',
        queryset=StateSenateDistrict.objects.exclude(abbrv=''),
    )
    state_house = django_filters.ModelMultipleChoiceFilter(
        name='state_house',
        label='State House District',
        queryset=StateHouseDistrict.objects.exclude(abbrv=''),
    )
    superior_court = django_filters.ModelMultipleChoiceFilter(
        name='superior_court',
        label='Superior Court District',
        queryset=SuperiorCourtDistrict.objects.exclude(abbrv=''),
    )
    histories_election_include = django_filters.ModelMultipleChoiceFilter(
        name='histories__election',
        label='Voted in',
        queryset=Election.objects.all(),
    )
    histories_election_exclude = django_filters.ModelMultipleChoiceFilter(
        name='histories__election',
        label='Did not vote in',
        queryset=Election.objects.all(),
        exclude=True,
    )

    class Meta:
        model = Voter
        exclude = [f.name for f in Voter._meta.get_fields()]
Exemple #19
0
class ProjectYearFilter(django_filters.FilterSet):
    is_hidden = django_filters.CharFilter(field_name='project__is_hidden')
    status = django_filters.NumberFilter(field_name='status')
    title = django_filters.CharFilter(field_name='project__title',
                                      lookup_expr="icontains")
    id = django_filters.NumberFilter(field_name='project__id')
    staff = django_filters.CharFilter(field_name='project__staff_search_field',
                                      lookup_expr="icontains")
    fiscal_year = django_filters.NumberFilter(field_name='fiscal_year')
    tag = django_filters.NumberFilter(field_name='project__tags')
    theme = django_filters.NumberFilter(
        field_name='project__functional_group__theme')
    functional_group = django_filters.NumberFilter(
        field_name='project__functional_group')
    funding_source = django_filters.NumberFilter(
        field_name='project__default_funding_source')
    region = django_filters.NumberFilter(
        field_name='project__section__division__branch__sector__region')
    division = django_filters.NumberFilter(
        field_name='project__section__division')
    section = django_filters.NumberFilter(field_name='project__section')
    starting_fy = django_filters.NumberFilter(
        field_name='project__starting_fy')
Exemple #20
0
class ChickenFilter(django_filters.FilterSet):

    min_id = django_filters.NumberFilter(name='id', lookup_expr='lte')
    max_id = django_filters.NumberFilter(name='id', lookup_expr='gte')

    date = django_filters.CharFilter(name='date', lookup_expr='exact')

    min_year = django_filters.NumberFilter(name='year', lookup_expr='lte')
    max_year = django_filters.NumberFilter(name='year', lookup_expr='gte')

    min_month = django_filters.NumberFilter(name='month', lookup_expr='lte')
    max_month = django_filters.NumberFilter(name='month', lookup_expr='gte')

    min_day = django_filters.NumberFilter(name='day', lookup_expr='lte')
    max_day = django_filters.NumberFilter(name='day', lookup_expr='gte')

    min_day_of_weeks = django_filters.NumberFilter(name='day_of_weeks',
                                                   lookup_expr='lte')
    max_day_of_weeks = django_filters.NumberFilter(name='day_of_weeks',
                                                   lookup_expr='gte')

    min_gender = django_filters.NumberFilter(name='gender', lookup_expr='lte')
    max_gender = django_filters.NumberFilter(name='gender', lookup_expr='gte')

    min_age = django_filters.NumberFilter(name='age', lookup_expr='lte')
    max_age = django_filters.NumberFilter(name='age', lookup_expr='gte')

    loc_mid = django_filters.CharFilter(name='loc_mid', lookup_expr='exact')

    min_call = django_filters.NumberFilter(name='call', lookup_expr='lte')
    max_call = django_filters.NumberFilter(name='call', lookup_expr='gte')

    class Meta:
        model = ChickenData
        fields = [
            'id', 'date', 'year', 'month', 'day', 'day_of_weeks', 'gender',
            'age', 'loc_mid', 'call'
        ]
Exemple #21
0
class DirectPeeringSessionFilterSet(BaseFilterSet, CreatedUpdatedFilterSet):
    q = django_filters.CharFilter(method="search", label="Search")
    local_autonomous_system_id = django_filters.ModelMultipleChoiceFilter(
        queryset=AutonomousSystem.objects.all(),
        label="Local AS (ID)",
    )
    local_autonomous_system_asn = django_filters.ModelMultipleChoiceFilter(
        field_name="local_autonomous_system__asn",
        queryset=AutonomousSystem.objects.all(),
        to_field_name="asn",
        label="Local AS (ASN)",
    )
    local_autonomous_system = django_filters.ModelMultipleChoiceFilter(
        field_name="local_autonomous_system__name",
        queryset=AutonomousSystem.objects.all(),
        to_field_name="name",
        label="Local AS (Name)",
    )
    autonomous_system_id = django_filters.ModelMultipleChoiceFilter(
        queryset=AutonomousSystem.objects.all(), label="Remote AS (ID)")
    autonomous_system_asn = django_filters.ModelMultipleChoiceFilter(
        field_name="autonomous_system__asn",
        queryset=AutonomousSystem.objects.all(),
        to_field_name="asn",
        label="Remote AS (ASN)",
    )
    autonomous_system = django_filters.ModelMultipleChoiceFilter(
        field_name="autonomous_system__name",
        queryset=AutonomousSystem.objects.all(),
        to_field_name="name",
        label="Remote AS (Name)",
    )
    bgp_group_id = django_filters.ModelMultipleChoiceFilter(
        queryset=BGPGroup.objects.all(), label="BGP Group (ID)")
    bgp_group = django_filters.ModelMultipleChoiceFilter(
        field_name="bgp_group__name",
        queryset=BGPGroup.objects.all(),
        to_field_name="name",
        label="BGP Group (Name)",
    )
    address_family = django_filters.NumberFilter(
        method="address_family_search")
    relationship = django_filters.MultipleChoiceFilter(
        choices=BGPRelationship.choices, null_value=None)
    router_id = django_filters.ModelMultipleChoiceFilter(
        queryset=Router.objects.all(), label="Router (ID)")
    router_name = django_filters.ModelMultipleChoiceFilter(
        field_name="router__name",
        queryset=Router.objects.all(),
        to_field_name="name",
        label="Router (Name)",
    )
    router = django_filters.ModelMultipleChoiceFilter(
        field_name="router__hostname",
        queryset=Router.objects.all(),
        to_field_name="hostname",
        label="Router (Hostname)",
    )
    tag = TagFilter()

    class Meta:
        model = DirectPeeringSession
        fields = ["id", "multihop_ttl", "enabled"]

    def search(self, queryset, name, value):
        if not value.strip():
            return queryset
        qs_filter = (Q(service_reference__icontains=value)
                     | Q(autonomous_system__name__icontains=value)
                     | Q(bgp_group__name__icontains=value)
                     | Q(bgp_group__slug__icontains=value)
                     | Q(router__name__icontains=value)
                     | Q(router__hostname__icontains=value))
        try:
            ip = ipaddress.ip_interface(value.strip())
            qs_filter |= Q(ip_address__host=str(ip)) | Q(
                local_ip_address__host=str(ip))
        except ValueError:
            pass
        return queryset.filter(qs_filter)

    def address_family_search(self, queryset, name, value):
        if value in [4, 6]:
            return queryset.filter(Q(ip_address__family=value))
        return queryset
Exemple #22
0
class MonsterInstanceFilter(django_filters.FilterSet):
    monster = django_filters.NumberFilter()
    monster__name = django_filters.CharFilter(method='filter_monster__name')
    tags__pk = django_filters.ModelMultipleChoiceFilter(
        queryset=MonsterTag.objects.all(), to_field_name='pk', conjoined=True)
    monster__element = django_filters.MultipleChoiceFilter(
        choices=Monster.ELEMENT_CHOICES)
    monster__archetype = django_filters.MultipleChoiceFilter(
        choices=Monster.ARCHETYPE_CHOICES)
    monster__awaken_level = django_filters.MultipleChoiceFilter(
        choices=Monster.AWAKEN_CHOICES)
    priority = django_filters.MultipleChoiceFilter(
        choices=MonsterInstance.PRIORITY_CHOICES)
    monster__leader_skill__attribute = django_filters.MultipleChoiceFilter(
        choices=LeaderSkill.ATTRIBUTE_CHOICES)
    monster__leader_skill__area = django_filters.MultipleChoiceFilter(
        choices=LeaderSkill.AREA_CHOICES)
    monster__skills__scaling_stats__pk = django_filters.ModelMultipleChoiceFilter(
        queryset=ScalingStat.objects.all(), to_field_name='pk', conjoined=True)
    monster__skills__effect__pk = django_filters.ModelMultipleChoiceFilter(
        queryset=SkillEffect.objects.all(),
        method='filter_monster__skills__effect__pk')
    monster__skills__passive = django_filters.BooleanFilter(
        method='filter_monster_skills_passive')
    effects_logic = django_filters.BooleanFilter(method='filter_effects_logic')
    monster__fusion_food = django_filters.BooleanFilter(
        method='filter_monster__fusion_food')

    class Meta:
        model = MonsterInstance
        fields = {
            'monster': ['exact'],
            'monster__name': ['exact'],
            'tags__pk': ['exact'],
            'stars': ['gte', 'lte'],
            'level': ['gte', 'lte'],
            'monster__element': ['exact'],
            'monster__archetype': ['exact'],
            'priority': ['exact'],
            'monster__awaken_level': ['exact'],
            'monster__leader_skill__attribute': ['exact'],
            'monster__leader_skill__area': ['exact'],
            'monster__skills__effect__pk': ['exact'],
            'monster__skills__scaling_stats__pk': ['exact'],
            'monster__skills__passive': ['exact'],
            'effects_logic': ['exact'],
            'fodder': ['exact'],
            'in_storage': ['exact'],
            'monster__fusion_food': ['exact'],
        }

    def filter_monster__name(self, queryset, name, value):
        if value:
            return queryset.filter(monster__name__istartswith=value)
        else:
            return queryset

    def filter_monster__fusion_food(self, queryset, name, value):
        if value:
            return queryset.filter(monster__fusion_food=True).exclude(
                ignore_for_fusion=True)
        else:
            return queryset.filter(
                Q(monster__fusion_food=False) | Q(ignore_for_fusion=True))

    def filter_monster__skills__effect__pk(self, queryset, name, value):
        old_filtering = self.form.cleaned_data.get('effects_logic', False)
        stat_scaling = self.form.cleaned_data.get(
            'monster__skills__scaling_stats__pk', [])
        passive = self.form.cleaned_data.get('monster__skills__passive', None)

        if old_filtering:
            # Filter if any skill on the monster has the designated fields
            for effect in value:
                queryset = queryset.filter(monster__skills__effect=effect)

            for pk in stat_scaling:
                queryset = queryset.filter(monster__skills__scaling_stats=pk)

            if passive is not None:
                queryset = queryset.filter(monster__skills__passive=passive, )

            return queryset.distinct()

        else:
            # Filter effects based on effects of each individual skill. This ensures a monster will not show up unless it has
            # the desired effects on the same skill rather than across any skills.

            skills = Skill.objects.all()

            for effect in value:
                skills = skills.filter(effect=effect)

            for pk in stat_scaling:
                skills = skills.filter(scaling_stats=pk)

            if passive is not None:
                skills = skills.filter(passive=passive, )

            return queryset.filter(monster__skills__in=skills).distinct()

    def filter_effects_logic(self, queryset, name, value):
        # This field is just used to alter the logic of skill effect filter and is used in filter_monster__skills__effect__pk()
        return queryset
Exemple #23
0
class SiteFilter(CustomFieldFilterSet, django_filters.FilterSet):
    id__in = NumericInFilter(field_name='id', lookup_expr='in')
    q = django_filters.CharFilter(
        method='search',
        label='Search',
    )
    status = django_filters.MultipleChoiceFilter(choices=SITE_STATUS_CHOICES,
                                                 null_value=None)
    region_id = django_filters.NumberFilter(
        method='filter_region',
        field_name='pk',
        label='Region (ID)',
    )
    region = django_filters.CharFilter(
        method='filter_region',
        field_name='slug',
        label='Region (slug)',
    )
    tenant_id = django_filters.ModelMultipleChoiceFilter(
        queryset=Tenant.objects.all(),
        label='Tenant (ID)',
    )
    tenant = django_filters.ModelMultipleChoiceFilter(
        field_name='tenant__slug',
        queryset=Tenant.objects.all(),
        to_field_name='slug',
        label='Tenant (slug)',
    )
    tag = TagFilter()

    class Meta:
        model = Site
        fields = [
            'q', 'name', 'slug', 'facility', 'asn', 'contact_name',
            'contact_phone', 'contact_email'
        ]

    def search(self, queryset, name, value):
        if not value.strip():
            return queryset
        qs_filter = (Q(name__icontains=value) | Q(facility__icontains=value)
                     | Q(description__icontains=value)
                     | Q(physical_address__icontains=value)
                     | Q(shipping_address__icontains=value)
                     | Q(contact_name__icontains=value)
                     | Q(contact_phone__icontains=value)
                     | Q(contact_email__icontains=value)
                     | Q(comments__icontains=value))
        try:
            qs_filter |= Q(asn=int(value.strip()))
        except ValueError:
            pass
        return queryset.filter(qs_filter)

    def filter_region(self, queryset, name, value):
        try:
            region = Region.objects.get(**{name: value})
        except ObjectDoesNotExist:
            return queryset.none()
        return queryset.filter(
            Q(region=region) | Q(region__in=region.get_descendants()))
Exemple #24
0
class HostFilter(BaseFilter):
    playbook = django_filters.NumberFilter(field_name="playbook__id",
                                           lookup_expr="exact")
    name = django_filters.CharFilter(field_name="name",
                                     lookup_expr="icontains")

    # For example: /api/v1/hosts/failed__gt=0 to return hosts with 1 failure or more
    changed__gt = django_filters.NumberFilter(field_name="changed",
                                              lookup_expr="gt")
    changed__lt = django_filters.NumberFilter(field_name="changed",
                                              lookup_expr="lt")
    failed__gt = django_filters.NumberFilter(field_name="failed",
                                             lookup_expr="gt")
    failed__lt = django_filters.NumberFilter(field_name="failed",
                                             lookup_expr="lt")
    ok__gt = django_filters.NumberFilter(field_name="ok", lookup_expr="gt")
    ok__lt = django_filters.NumberFilter(field_name="ok", lookup_expr="lt")
    skipped__gt = django_filters.NumberFilter(field_name="skipped",
                                              lookup_expr="gt")
    skipped__lt = django_filters.NumberFilter(field_name="skipped",
                                              lookup_expr="lt")
    unreachable__gt = django_filters.NumberFilter(field_name="unreachable",
                                                  lookup_expr="gt")
    unreachable__lt = django_filters.NumberFilter(field_name="unreachable",
                                                  lookup_expr="lt")

    # fmt: off
    order = django_filters.OrderingFilter(fields=(
        ("id", "id"),
        ("created", "created"),
        ("updated", "updated"),
        ("name", "name"),
        ("changed", "changed"),
        ("failed", "failed"),
        ("ok", "ok"),
        ("skipped", "skipped"),
        ("unreachable", "unreachable"),
    ))
Exemple #25
0
class PrefixFilter(CustomFieldFilterSet, django_filters.FilterSet):
    id__in = NumericInFilter(name='id', lookup_expr='in')
    q = django_filters.CharFilter(
        method='search',
        label='Search',
    )
    # TODO: Deprecate in v2.3.0
    parent = django_filters.CharFilter(
        method='search_within_include',
        label='Parent prefix (deprecated)',
    )
    within = django_filters.CharFilter(
        method='search_within',
        label='Within prefix',
    )
    within_include = django_filters.CharFilter(
        method='search_within_include',
        label='Within and including prefix',
    )
    mask_length = django_filters.NumberFilter(
        method='filter_mask_length',
        label='Mask length',
    )
    vrf_id = django_filters.ModelMultipleChoiceFilter(
        queryset=VRF.objects.all(),
        label='VRF',
    )
    vrf = django_filters.ModelMultipleChoiceFilter(
        name='vrf__rd',
        queryset=VRF.objects.all(),
        to_field_name='rd',
        label='VRF (RD)',
    )
    tenant_id = django_filters.ModelMultipleChoiceFilter(
        queryset=Tenant.objects.all(),
        label='Tenant (ID)',
    )
    tenant = django_filters.ModelMultipleChoiceFilter(
        name='tenant__slug',
        queryset=Tenant.objects.all(),
        to_field_name='slug',
        label='Tenant (slug)',
    )
    site_id = django_filters.ModelMultipleChoiceFilter(
        queryset=Site.objects.all(),
        label='Site (ID)',
    )
    site = django_filters.ModelMultipleChoiceFilter(
        name='site__slug',
        queryset=Site.objects.all(),
        to_field_name='slug',
        label='Site (slug)',
    )
    vlan_id = django_filters.ModelMultipleChoiceFilter(
        queryset=VLAN.objects.all(),
        label='VLAN (ID)',
    )
    vlan_vid = django_filters.NumberFilter(
        name='vlan__vid',
        label='VLAN number (1-4095)',
    )
    role_id = django_filters.ModelMultipleChoiceFilter(
        queryset=Role.objects.all(),
        label='Role (ID)',
    )
    role = django_filters.ModelMultipleChoiceFilter(
        name='role__slug',
        queryset=Role.objects.all(),
        to_field_name='slug',
        label='Role (slug)',
    )
    status = django_filters.MultipleChoiceFilter(choices=PREFIX_STATUS_CHOICES,
                                                 null_value=None)

    class Meta:
        model = Prefix
        fields = ['family', 'is_pool']

    def search(self, queryset, name, value):
        if not value.strip():
            return queryset
        qs_filter = Q(description__icontains=value)
        try:
            prefix = str(IPNetwork(value.strip()).cidr)
            qs_filter |= Q(prefix__net_contains_or_equals=prefix)
        except (AddrFormatError, ValueError):
            pass
        return queryset.filter(qs_filter)

    def search_within(self, queryset, name, value):
        value = value.strip()
        if not value:
            return queryset
        try:
            query = str(IPNetwork(value).cidr)
            return queryset.filter(prefix__net_contained=query)
        except (AddrFormatError, ValueError):
            return queryset.none()

    def search_within_include(self, queryset, name, value):
        value = value.strip()
        if not value:
            return queryset
        try:
            query = str(IPNetwork(value).cidr)
            return queryset.filter(prefix__net_contained_or_equal=query)
        except (AddrFormatError, ValueError):
            return queryset.none()

    def filter_mask_length(self, queryset, name, value):
        if not value:
            return queryset
        return queryset.filter(prefix__net_mask_length=value)
Exemple #26
0
class CaseAnnotationFilter(FilterSet):
    belongs_to = django_filters.NumberFilter()
    label = django_filters.NumberFilter()
Exemple #27
0
class ChannelFilter(GenericDateFilterSet):
    user = django_filters.NumberFilter(name='channeluser__user')

    class Meta:
        model = Channel
        fields = ('user', 'type')
Exemple #28
0
class AnnotationLabelFilter(FilterSet):
    owner = django_filters.NumberFilter()
    slug = django_filters.CharFilter()
    private = django_filters.BooleanFilter()
    trusted = django_filters.BooleanFilter()
Exemple #29
0
class InterfaceFilter(django_filters.FilterSet):
    """
    Not using DeviceComponentFilterSet for Interfaces because we need to check for VirtualChassis membership.
    """
    q = django_filters.CharFilter(
        method='search',
        label='Search',
    )
    device = django_filters.CharFilter(
        method='filter_device',
        field_name='name',
        label='Device',
    )
    device_id = django_filters.NumberFilter(
        method='filter_device',
        field_name='pk',
        label='Device (ID)',
    )
    cabled = django_filters.BooleanFilter(field_name='cable',
                                          lookup_expr='isnull',
                                          exclude=True)
    type = django_filters.CharFilter(
        method='filter_type',
        label='Interface type',
    )
    lag_id = django_filters.ModelMultipleChoiceFilter(
        field_name='lag',
        queryset=Interface.objects.all(),
        label='LAG interface (ID)',
    )
    mac_address = django_filters.CharFilter(
        method='_mac_address',
        label='MAC address',
    )
    tag = TagFilter()
    vlan_id = django_filters.CharFilter(method='filter_vlan_id',
                                        label='Assigned VLAN')
    vlan = django_filters.CharFilter(method='filter_vlan',
                                     label='Assigned VID')
    form_factor = django_filters.MultipleChoiceFilter(choices=IFACE_FF_CHOICES,
                                                      null_value=None)

    class Meta:
        model = Interface
        fields = [
            'name', 'connection_status', 'form_factor', 'enabled', 'mtu',
            'mgmt_only'
        ]

    def search(self, queryset, name, value):
        if not value.strip():
            return queryset
        return queryset.filter(Q(name__icontains=value)).distinct()

    def filter_device(self, queryset, name, value):
        try:
            device = Device.objects.get(**{name: value})
            vc_interface_ids = device.vc_interfaces.values_list('id',
                                                                flat=True)
            return queryset.filter(pk__in=vc_interface_ids)
        except Device.DoesNotExist:
            return queryset.none()

    def filter_vlan_id(self, queryset, name, value):
        value = value.strip()
        if not value:
            return queryset
        return queryset.filter(
            Q(untagged_vlan_id=value) | Q(tagged_vlans=value))

    def filter_vlan(self, queryset, name, value):
        value = value.strip()
        if not value:
            return queryset
        return queryset.filter(
            Q(untagged_vlan_id__vid=value) | Q(tagged_vlans__vid=value))

    def filter_type(self, queryset, name, value):
        value = value.strip().lower()
        return {
            'physical':
            queryset.exclude(form_factor__in=NONCONNECTABLE_IFACE_TYPES),
            'virtual':
            queryset.filter(form_factor__in=VIRTUAL_IFACE_TYPES),
            'wireless':
            queryset.filter(form_factor__in=WIRELESS_IFACE_TYPES),
            'lag':
            queryset.filter(form_factor=IFACE_FF_LAG),
        }.get(value, queryset.none())

    def _mac_address(self, queryset, name, value):
        value = value.strip()
        if not value:
            return queryset
        try:
            mac = EUI(value.strip())
            return queryset.filter(mac_address=mac)
        except AddrFormatError:
            return queryset.none()
Exemple #30
0
class IPAddressFilter(CustomFieldFilterSet, django_filters.FilterSet):
    id__in = NumericInFilter(name='id', lookup_expr='in')
    q = django_filters.CharFilter(
        method='search',
        label='Search',
    )
    parent = django_filters.CharFilter(
        method='search_by_parent',
        label='Parent prefix',
    )
    mask_length = django_filters.NumberFilter(
        method='filter_mask_length',
        label='Mask length',
    )
    vrf_id = NullableModelMultipleChoiceFilter(
        name='vrf_id',
        queryset=VRF.objects.all(),
        label='VRF',
    )
    vrf = NullableModelMultipleChoiceFilter(
        name='vrf',
        queryset=VRF.objects.all(),
        to_field_name='rd',
        label='VRF (RD)',
    )
    tenant_id = NullableModelMultipleChoiceFilter(
        name='tenant',
        queryset=Tenant.objects.all(),
        label='Tenant (ID)',
    )
    tenant = NullableModelMultipleChoiceFilter(
        name='tenant',
        queryset=Tenant.objects.all(),
        to_field_name='slug',
        label='Tenant (slug)',
    )
    device_id = django_filters.ModelMultipleChoiceFilter(
        name='interface__device',
        queryset=Device.objects.all(),
        label='Device (ID)',
    )
    device = django_filters.ModelMultipleChoiceFilter(
        name='interface__device__name',
        queryset=Device.objects.all(),
        to_field_name='name',
        label='Device (name)',
    )
    interface_id = django_filters.ModelMultipleChoiceFilter(
        name='interface',
        queryset=Interface.objects.all(),
        label='Interface (ID)',
    )

    class Meta:
        model = IPAddress
        fields = ['family', 'status']

    def search(self, queryset, name, value):
        if not value.strip():
            return queryset
        qs_filter = Q(description__icontains=value)
        try:
            ipaddress = str(IPNetwork(value.strip()))
            qs_filter |= Q(address__net_host=ipaddress)
        except AddrFormatError:
            pass
        return queryset.filter(qs_filter)

    def search_by_parent(self, queryset, name, value):
        value = value.strip()
        if not value:
            return queryset
        try:
            query = str(IPNetwork(value.strip()).cidr)
            return queryset.filter(address__net_host_contained=query)
        except AddrFormatError:
            return queryset.none()

    def filter_mask_length(self, queryset, name, value):
        if not value:
            return queryset
        return queryset.filter(address__net_mask_length=value)