Ejemplo n.º 1
0
class FeeChargeFilter(django_filters.FilterSet):

    collab = CollaborationFilter(label=_('Colaboración'),
                                 collab_field='collab__collaboration')
    search = AccountSearchFilter(names=['payment__concept', 'account__cif'],
                                 lookup_expr='in',
                                 label=_('Buscar...'))
    o = LabeledOrderingFilter(fields=['payment__amount', 'payment__added'],
                              field_labels={
                                  'payment__amount': 'Cuota',
                                  'account__member_type': 'Tipo de socia',
                                  'payment__added': 'Fecha de emisión'
                              })
    uncalculated = django_filters.BooleanFilter(
        field_name='payment',
        lookup_expr='isnull',
        widget=BooleanWidget(attrs={'class': 'threestate'}),
        label=_('Cuota sin calcular'))
    account__member_type = django_filters.ChoiceFilter(
        choices=settings.MEMBER_TYPES, label=_('Tipo de socia:'))
    paid = django_filters.BooleanFilter(
        field_name='payment__completed',
        widget=BooleanWidget(attrs={'class': 'threestate'}),
        label=_('Pagado'))

    class Meta:
        model = AccountAnnualFeeCharge
        form = FeeChargeFilterForm
        fields = {'account__member_type': ['exact']}
Ejemplo n.º 2
0
    def get_serializer_class(self):
        if self.action == "create":
            return InvoiceCreateSerializer

        if self.action in ("update", "partial_update", "metadata"):
            if "pk" in self.kwargs:
                instance = self.get_object()
                if instance:
                    if instance.sent_to_sap_at:
                        return SentToSapInvoiceUpdateSerializer

                    if instance.type == InvoiceType.CREDIT_NOTE:
                        return CreditNoteUpdateSerializer

                    if instance.generated:
                        return GeneratedInvoiceUpdateSerializer

            return InvoiceUpdateSerializer

        if self.request.query_params.get("going_to_sap"):
            boolean_widget = BooleanWidget()
            # check passed value against widget's truthy values
            if boolean_widget.value_from_datadict(self.request.query_params,
                                                  None, "going_to_sap"):
                return InvoiceSerializerWithSuccinctLease

        return InvoiceSerializer
Ejemplo n.º 3
0
 def test_widget_render(self):
     w = BooleanWidget()
     self.assertHTMLEqual(w.render('price', ''), """
         <select name="price">
             <option selected="selected" value="">Unknown</option>
             <option value="true">Yes</option>
             <option value="false">No</option>
         </select>""")
Ejemplo n.º 4
0
 def test_widget_render(self):
     w = BooleanWidget()
     self.assertHTMLEqual(w.render('price', ''), """
         <select name="price">
             <option selected="selected" value="">Unknown</option>
             <option value="true">Yes</option>
             <option value="false">No</option>
         </select>""")
Ejemplo n.º 5
0
class DomainFilter(django_filters.FilterSet):
    keyword = django_filters.CharFilter(lookup_expr='icontains')
    tk = django_filters.BooleanFilter(field_name='tk', widget=BooleanWidget())
    ml = django_filters.BooleanFilter(field_name='ml', widget=BooleanWidget())
    ga = django_filters.BooleanFilter(field_name='ga', widget=BooleanWidget())
    cf = django_filters.AllValuesMultipleFilter(field_name='cf',
                                                widget=CheckboxInput())

    class Meta:
        model = Domain
        fields = ['keyword', 'tk', 'ml', 'ga', 'cf']
Ejemplo n.º 6
0
class ServiceProviderFilter(df_filters.FilterSet):
    """
    Filters for ServiceProvider view.
    """
    admins__username = df_filters.CharFilter(lookup_expr='icontains')
    admin_groups__name = df_filters.CharFilter(lookup_expr='icontains')
    notes = df_filters.CharFilter(lookup_expr='icontains')
    production = df_filters.BooleanFilter(field_name='production', widget=BooleanWidget())
    test = df_filters.BooleanFilter(field_name='test', widget=BooleanWidget())

    class Meta:
        model = ServiceProvider
        fields = ['entity_id', 'production', 'test', 'admins__username', 'admin_groups__name', 'notes']
Ejemplo n.º 7
0
class UserFilter(FilterSet):
    class Meta:
        model = User
        fields = ['email', 'username', 'first_name', 'last_name', 'is_manager', 'is_staff', 'is_superuser', 'is_active',
                  'created']

    email = CharFilter(label="Email contient", lookup_expr='icontains')
    first_name = CharFilter(lookup_expr='icontains')
    last_name = CharFilter(lookup_expr='icontains')
    username = CharFilter(label="Username", lookup_expr='icontains')
    created = DateTimeFilter(label="Cree le", lookup_expr="icontains")
    is_superuser = BooleanFilter(label="Admin", widget=BooleanWidget())
    is_manager = BooleanFilter(label="Chef de Projet", widget=BooleanWidget())
    is_active = BooleanFilter(label="Active", widget=BooleanWidget())
    is_staff = BooleanFilter(label="Staff", widget=BooleanWidget())
Ejemplo n.º 8
0
    def test_widget_value_from_datadict(self):
        """
        """
        w = BooleanWidget()

        trueActive = {'active': 'true'}
        result = w.value_from_datadict(trueActive, {}, 'active')
        self.assertEqual(result, True)

        falseActive = {'active': 'false'}
        result = w.value_from_datadict(falseActive, {}, 'active')
        self.assertEqual(result, False)

        result = w.value_from_datadict({}, {}, 'active')
        self.assertEqual(result, None)
Ejemplo n.º 9
0
    def test_widget_value_from_datadict(self):
        """
        """
        w = BooleanWidget()

        trueActive = {'active': 'true'}
        result = w.value_from_datadict(trueActive, {}, 'active')
        self.assertEqual(result, True)

        falseActive = {'active': 'false'}
        result = w.value_from_datadict(falseActive, {}, 'active')
        self.assertEqual(result, False)

        result = w.value_from_datadict({}, {}, 'active')
        self.assertEqual(result, None)
Ejemplo n.º 10
0
class ContestFilter(django_filters.FilterSet):
    name = django_filters.CharFilter(lookup_expr='icontains', label='name')
    group = django_filters.ModelChoiceFilter(
        queryset=GroupProfile.objects.all())
    can_manage = django_filters.BooleanFilter(method='filter_can_manage',
                                              label='can_manage',
                                              widget=BooleanWidget())

    def filter_can_manage(self, queryset, name, value):
        groups = get_objects_for_user(self.user,
                                      'ojuser.change_groupprofile',
                                      with_superuser=True).distinct()
        if value:
            return queryset.filter(pk__in=groups)
        else:
            return queryset.exclude(pk__in=groups)

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user', None)
        super(ContestFilter, self).__init__(*args, **kwargs)
        self.filters.get('group').queryset = get_objects_for_user(
            self.user, 'ojuser.view_groupprofile', with_superuser=True)

    class Meta:
        model = Contest
        fields = [
            'name',
            'group',
            'can_manage',
        ]
Ejemplo n.º 11
0
class GroupFilter(django_filters.FilterSet):
    name = django_filters.CharFilter(lookup_expr='icontains')
    can_manage = django_filters.BooleanFilter(method='filter_can_manage',
                                              label='can_manage',
                                              widget=BooleanWidget())

    def filter_can_manage(self, queryset, name, value):
        print "<name>:", name
        print "<value>:", value
        profiles_can_change = get_objects_for_user(
            self.user, 'ojuser.change_groupprofile', with_superuser=True)
        if value:
            queryset = queryset.filter(pk__in=profiles_can_change)
        else:
            queryset = queryset.exclude(pk__in=profiles_can_change)

        return queryset

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user', None)
        super(GroupFilter, self).__init__(*args, **kwargs)

    class Meta:
        model = Group
        fields = [
            'name',
            'can_manage',
        ]
Ejemplo n.º 12
0
class ProfileFilter(django_filters.FilterSet):

    #acceptedCurrencies = django_filters.Filter(name='moderator_accepted_currencies', lookup_expr='icontains')
    rating = django_filters.Filter(name='rating_average', lookup_expr='gte')
    version = django_filters.Filter(name='user_agent', lookup_expr='icontains')
    moderator_languages = django_filters.Filter(name='moderator_languages',
                                                lookup_expr='contains')
    has_email = django_filters.Filter(name='email',
                                      lookup_expr='isnull',
                                      exclude=True,
                                      widget=BooleanWidget())
    has_website = django_filters.Filter(name='website',
                                        lookup_expr='isnull',
                                        exclude=True,
                                        widget=BooleanWidget())
    is_moderator = django_filters.BooleanFilter(name='moderator',
                                                lookup_expr='exact',
                                                widget=BooleanWidget())
    is_verified = django_filters.Filter(name='verified',
                                        exclude=False,
                                        widget=TruthyWidget())
    has_verified = django_filters.Filter(name='listing__moderators__verified',
                                         widget=TruthyWidget())
    moderator_count = django_filters.NumberFilter(
        method='filter_listing_by_moderator_count')
    connection = django_filters.TypedChoiceFilter(
        name='connection_type', choices=Profile.CONNECTION_TYPE_CHOICES)
    online = django_filters.Filter(name='online', widget=TruthyWidget())

    #pgp_block = django_filters.BooleanFilter(name='description', method='filter_published')

    class Meta:
        model = Profile
        exclude = ()
        order_by = True
        filter_overrides = {
            ArrayField: {
                'filter_class': django_filters.CharFilter,
                'extra': lambda f: {
                    'lookup_expr': 'icontains',
                },
            },
        }

    def filter_listing_by_moderator_count(self, queryset, name, value):
        return queryset.filter(moderators_count__gte=value)
Ejemplo n.º 13
0
class ReservationFilter(FilterSet):
    start_gte = IsoDateTimeFilter('start', lookup_expr='gte')
    start_lt = IsoDateTimeFilter('start', lookup_expr='lt')
    missed = BooleanFilter('missed', widget=BooleanWidget())

    class Meta:
        model = Reservation
        fields = []
Ejemplo n.º 14
0
class CouncilElectionIsConfirmedFilter(django_filters.FilterSet):
    confirmed = django_filters.BooleanFilter(widget=BooleanWidget())

    class Meta:
        model = CouncilElection
        fields = [
            'confirmed',
        ]
Ejemplo n.º 15
0
class ProfileFilter(df.FilterSet):

    rating = df.Filter(field_name='rating_average', lookup_expr='gte')
    user_agent = df.Filter(field_name='user_agent', lookup_expr='icontains')
    moderator_languages = df.Filter(field_name='moderator_languages',
                                    lookup_expr='contains')
    has_email = df.Filter(field_name='email',
                          lookup_expr='isnull',
                          exclude=True,
                          widget=BooleanWidget())
    has_website = df.Filter(field_name='website',
                            lookup_expr='isnull',
                            exclude=True,
                            widget=BooleanWidget())
    is_moderator = df.BooleanFilter(field_name='moderator',
                                    lookup_expr='exact',
                                    widget=BooleanWidget())
    is_verified = df.Filter(field_name='verified',
                            exclude=False,
                            widget=TruthyWidget())
    has_verified = df.Filter(field_name='listing__moderators__verified',
                             widget=TruthyWidget())
    moderator_count = df.NumberFilter(
        method='filter_listing_by_moderator_count')
    connection = df.TypedChoiceFilter(field_name='connection_type',
                                      choices=Profile.CONNECTION_TYPE_CHOICES)
    online = df.Filter(field_name='online', widget=TruthyWidget())

    class Meta:
        model = Profile
        filter_overrides = {
            ArrayField: {
                'filter_class': df.CharFilter,
                'extra': lambda f: {
                    'lookup_expr': 'icontains',
                },
            },
        }
        exclude = ['nsfw']
        order_by = True

    def filter_listing_by_moderator_count(self, queryset, name, value):
        return queryset.filter(moderators_count__gte=value)
Ejemplo n.º 16
0
class VenueFilterForm(django_filters.FilterSet):
    CHOICES = ((1, 'Active'), (0, 'Inactive'))
    venue_status = django_filters.BooleanFilter(widget=BooleanWidget(
        attrs={"class": "form-control"}))

    venue_name = django_filters.CharFilter(lookup_expr='icontains')
    venue_mobile = django_filters.CharFilter(lookup_expr='icontains')

    class Meta:
        model = Venue
        fields = "__all__"
Ejemplo n.º 17
0
class ProductFilter(django_filters.FilterSet):
    active = django_filters.BooleanFilter(field_name='active',
                                          widget=BooleanWidget())

    class Meta:
        model = Product
        fields = {
            'sku': ['icontains'],
            'name': ['icontains'],
            'description': ['icontains']
        }
Ejemplo n.º 18
0
class RecordListFilter(filters.FilterSet):
    """
    Filters for RecordList view.
    """
    category = NumberInFilter(field_name='category__pk', lookup_expr='in')
    level = NumberInFilter(field_name='level__pk', lookup_expr='in')
    type = NumberInFilter(field_name='type__pk', lookup_expr='in')
    sport = NumberInFilter(field_name='type__sport__pk', lookup_expr='in')
    historical = filters.BooleanFilter(field_name='historical', widget=BooleanWidget())
    approved = filters.BooleanFilter(field_name='approved', widget=BooleanWidget())
    start = filters.DateFilter(field_name='date_start', lookup_expr='gte')
    end = filters.DateFilter(field_name='date_end', lookup_expr='lte')

    o = filters.OrderingFilter(
        fields=(
            ('type', 'type'),
            ('category', 'category'),
            ('approved', 'approved'),
            ('level', 'level'),
        )
    )
Ejemplo n.º 19
0
class IntercoopAccountFilter(django_filters.FilterSet):

    search = SearchFilter(names=['first_name', 'last_name', 'contact_email'], lookup_expr='in', label=_('Buscar...'))
    o = LabeledOrderingFilter(fields=['name', 'registration_date', 'expiration_date'], field_labels={'name':'Nombre', 'registration_date':'Fecha de registro', 'expiration_date':'Fecha de expiración'})
    validated = django_filters.BooleanFilter(field_name='validated',
                                             widget=BooleanWidget(attrs={'class': 'threestate'}))


    class Meta:
        model = IntercoopAccount
        form = IntercoopAccountFilterForm
        fields = { 'entity':['exact']}
Ejemplo n.º 20
0
class PendingPaymentFilter(django_filters.FilterSet):

    search = AccountSearchFilter(names=['concept', 'account__cif'],
                                 lookup_expr='in',
                                 label=_('Buscar...'))
    o = LabeledOrderingFilter(choices=(('-added', 'Fecha de emisión'),
                                       ('-amount', 'Cantidad (descendente)'),
                                       ('-timestamp', 'Fecha de pago'),
                                       ('-sepa_batches__attempt',
                                        'Añadido a remesa')))
    account = MemberTypeFilter(label='Tipo de socia')
    completed = django_filters.BooleanFilter(
        field_name='completed',
        widget=BooleanWidget(attrs={'class': 'threestate'}))
    returned = django_filters.BooleanFilter(
        field_name='returned',
        widget=BooleanWidget(attrs={'class': 'threestate'}))

    class Meta:
        model = PendingPayment
        form = PendingPaymentFilterForm
        fields = {}
Ejemplo n.º 21
0
class PendingPaymentFilter(django_filters.FilterSet):

    search = SearchFilter(names=['concept', 'account__contact_email'],
                          lookup_expr='in',
                          label=_('Buscar...'))
    o = LabeledOrderingFilter(fields=['amount', 'added', 'timestamp'],
                              field_labels={
                                  'amount': 'Cantidad',
                                  'added': 'Añadido',
                                  'timestamp': 'Pagado'
                              })
    account = MemberTypeFilter(label='Tipo de socia')
    completed = django_filters.BooleanFilter(
        field_name='completed',
        widget=BooleanWidget(attrs={'class': 'threestate'}))
    returned = django_filters.BooleanFilter(
        field_name='returned',
        widget=BooleanWidget(attrs={'class': 'threestate'}))

    class Meta:
        model = PendingPayment
        form = PendingPaymentFilterForm
        fields = {}
Ejemplo n.º 22
0
class UserFilter(django_filters.FilterSet):

    search = SearchFilter(
        names=['username', 'first_name', 'last_name', 'email'],
        lookup_expr='in',
        label=_('Buscar...'))
    o = LabeledOrderingFilter(fields=['username', 'last_login', 'date_joined'])
    is_active = django_filters.BooleanFilter(
        field_name='is_active',
        widget=BooleanWidget(attrs={'class': 'threestate'}))

    class Meta:
        model = User
        form = UserFilterForm
        fields = {}
Ejemplo n.º 23
0
class ServiceFilter(filters.FilterSet):
    consent_given = filters.Filter(
        method='filter_consent_given', widget=BooleanWidget(),
        help_text=_('Include only services that have or don\'t have a consent given by the current user. '
                    'Accepts boolean values "true" and "false".'))

    class Meta:
        model = Service
        fields = ('consent_given',)

    def filter_consent_given(self, queryset, name, value):
        if 'consent_given' in queryset.query.annotations.keys():
            queryset = queryset.filter(consent_given=value)

        return queryset
Ejemplo n.º 24
0
    def get_serializer_class(self):
        if self.action == 'create':
            return InvoiceCreateSerializer

        if self.action in ('update', 'partial_update', 'metadata'):
            if 'pk' in self.kwargs:
                instance = self.get_object()
                if instance:
                    if instance.type == InvoiceType.CREDIT_NOTE:
                        return CreditNoteUpdateSerializer

                    if instance.generated:
                        return GeneratedInvoiceUpdateSerializer

            return InvoiceUpdateSerializer

        if self.request.query_params.get('going_to_sap'):
            boolean_widget = BooleanWidget()
            # check passed value against widget's truthy values
            if boolean_widget.value_from_datadict(self.request.query_params,
                                                  None, 'going_to_sap'):
                return InvoiceSerializerWithSuccinctLease

        return InvoiceSerializer
Ejemplo n.º 25
0
class BalanceFilter(django_filters.FilterSet):

    search = AccountSearchFilter(names=['sponsor__username', 'account__cif'],
                                 lookup_expr='in',
                                 label=_('Buscar...'))
    o = LabeledOrderingFilter(fields=['account', 'last_update'],
                              field_labels={
                                  'account': 'Nombre',
                                  'last_update': 'Última actualización'
                              })
    status = WorkflowFilter(['social_balance'],
                            filter_cancelled=True,
                            label='Estado')
    sponsor = SponsorFilter(
        label=_('Amadrinada por mí'),
        widget=BooleanWidget(attrs={'class': 'threestate'}))

    class Meta:
        form = BalanceFilterForm
        fields = {}
Ejemplo n.º 26
0
class MappingTeamFilter(filters.FilterSet):
    trusted = filters.BooleanFilter(
        field_name='trusted',
        widget=BooleanWidget(),
        help_text="""Filter Mapping Teams that were trusted by a staff user."""
    )
    name = filters.CharFilter(
        field_name='name',
        lookup_expr='icontains',
        help_text="""Filter Mapping Teams by its name field using the icontains
            lookup expression.""")
    owner = filters.CharFilter(
        field_name='created_by__username',
        lookup_expr='exact',
        help_text="""Filter Mapping Teams by the username of the user that
            created it. This field uses the exact lookup expression.""")

    class Meta:
        model = MappingTeam
        fields = []
Ejemplo n.º 27
0
class ReservationFilter(filters.FilterSet):
    client_name = filters.CharFilter(field_name='client__name', lookup_expr='iexact')
    client_name__istartswith = filters.CharFilter(field_name='client__name', lookup_expr='istartswith')
    client_name__icontains = filters.CharFilter(field_name='client__name', lookup_expr='icontains')
    client_username = filters.CharFilter(field_name='client__username', lookup_expr='iexact')
    client_username__istartswith = filters.CharFilter(field_name='client__username', lookup_expr='istartswith')
    client_username__icontains = filters.CharFilter(field_name='client__username', lookup_expr='icontains')
    book_title = filters.CharFilter(field_name='book__title', lookup_expr='iexact')
    book_title__istartswith = filters.CharFilter(field_name='book__title', lookup_expr='istartswith')
    book_title__icontains = filters.CharFilter(field_name='book__title', lookup_expr='icontains')
    book_author = filters.CharFilter(field_name='book__author', lookup_expr='iexact')
    book_author__istartswith = filters.CharFilter(field_name='book__author', lookup_expr='istartswith')
    book_author__icontains = filters.CharFilter(field_name='book__author', lookup_expr='icontains')
    reserved_at = filters.DateFilter(field_name='reserved_at', lookup_expr='contains')
    returned_at = filters.DateFilter(field_name='returned_at', lookup_expr='contains')
    active = filters.BooleanFilter(field_name='active', widget=BooleanWidget())

    class Meta:
        model = models.Reservation
        fields = [
            'client_name',
            'client_username',
            'book_title',
            'book_author',
            'reserved_at',
            'returned_at',
            'active',
        ]

    ordering = OrderingFilter(
        fields=[
            ('client__name', 'client_name'),
            ('client__username', 'client_username'),
            ('book__title', 'book_title'),
            ('book__author', 'book_author'),
            *get_fields_tuple(Meta.model),
        ],
        label=f'Ordenation of {Meta.model.__name__}s'
    )
Ejemplo n.º 28
0
class BookFilter(filters.FilterSet):
    title = filters.CharFilter(field_name='title', lookup_expr='iexact')
    title__istartswith = filters.CharFilter(field_name='title', lookup_expr='istartswith')
    title__icontains = filters.CharFilter(field_name='title', lookup_expr='icontains')
    subtitle = filters.CharFilter(field_name='subtitle', lookup_expr='iexact')
    subtitle__istartswith = filters.CharFilter(field_name='subtitle', lookup_expr='istartswith')
    subtitle__icontains = filters.CharFilter(field_name='subtitle', lookup_expr='icontains')
    author = filters.CharFilter(field_name='author', lookup_expr='iexact')
    author__istartswith = filters.CharFilter(field_name='author', lookup_expr='istartswith')
    author__icontains = filters.CharFilter(field_name='author', lookup_expr='icontains')
    isbn = filters.CharFilter(field_name='isbn', lookup_expr='iexact')
    isbn__istartswith = filters.CharFilter(field_name='isbn', lookup_expr='istartswith')
    isbn__icontains = filters.CharFilter(field_name='isbn', lookup_expr='icontains')
    reservation_price = filters.NumberFilter(field_name='reservation_price', lookup_expr='exact')
    reservation_price_ne = filters.NumberFilter(field_name='reservation_price', lookup_expr='ne')
    reservation_price_lt = filters.NumberFilter(field_name='reservation_price', lookup_expr='lt')
    reservation_price_gt = filters.NumberFilter(field_name='reservation_price', lookup_expr='gt')
    reservation_price_lte = filters.NumberFilter(field_name='reservation_price', lookup_expr='lte')
    reservation_price_gte = filters.NumberFilter(field_name='reservation_price', lookup_expr='gte')
    reserved = filters.BooleanFilter(field_name='reserved', widget=BooleanWidget())

    class Meta:
        model = models.Book
        fields = [
            'title',
            'subtitle',
            'author',
            'isbn',
            'reservation_price',
            'reserved',
        ]

    ordering = OrderingFilter(
        fields=[
            *get_fields_tuple(Meta.model),
        ],
        label=f'Ordenation of {Meta.model.__name__}s'
    )
Ejemplo n.º 29
0
class ChangesetFilter(GeoFilterSet):
    """Allows to filter Changesets by any of its fields, except 'uuid' (id of
    OSM user). The 'reasons' and the 'harmful_reasons' fields can be filtered
    by the exact match (filter changesets that have all the search reasons) or
    by contains match (filter changesets that have any of the reasons).
    """
    geometry = GeometryFilter(
        field_name='bbox',
        lookup_expr='intersects',
        help_text="""Geospatial filter of changeset whose bbox intersects with
            another geometry. You can use any geometry type in this filter.""")
    checked_by = filters.CharFilter(
        field_name='check_user',
        method='filter_checked_by',
        help_text="""Filter changesets that were checked by a user. Use commas
            to search for more than one user.""")
    users = filters.CharFilter(
        field_name='user',
        method='filter_users',
        help_text="""Filter changesets created by a user. Use commas to search
            for more than one user.""")
    ids = filters.CharFilter(
        field_name='id',
        method='filter_ids',
        help_text="""Filter changesets by its ID. Use commas to search for more
            than one id.""")
    uids = filters.CharFilter(
        field_name='uid',
        method='filter_uids',
        help_text="""Filter changesets by its uid. The uid is a unique identifier
        of each user in OSM. Use commas to search for more than one uid.""")
    checked = filters.BooleanFilter(
        field_name='checked',
        widget=BooleanWidget(),
        help_text="""Filter changesets that were checked or not. Use true/false,
            1/0 values.""")
    harmful = filters.BooleanFilter(
        field_name='harmful',
        widget=BooleanWidget(),
        help_text="""Filter changesets that were marked as harmful or not.
            Use true/false, 1/0 values.""")
    is_suspect = filters.BooleanFilter(
        field_name='is_suspect',
        widget=BooleanWidget(),
        help_text='Filter changesets that were considered suspect by OSMCHA.')
    powerfull_editor = filters.BooleanFilter(
        field_name='powerfull_editor',
        widget=BooleanWidget(),
        help_text="""Filter changesets that were created using a software editor
            considered powerfull (those that allow to create, modify or delete
            data in a batch).""")
    order_by = filters.CharFilter(
        field_name='order',
        method='order_queryset',
        help_text="""Order the Changesets by one of the following fields: id,
            date, check_date, create, modify, delete or number_reasons. Use a
            minus sign (-) before the field name to reverse the ordering.
            Default ordering is '-id'.""")
    hide_whitelist = filters.BooleanFilter(
        field_name='user',
        method='filter_whitelist',
        widget=BooleanWidget(),
        help_text="""If True, it will exclude the changesets created by the
            users that you whitelisted.""")
    blacklist = filters.BooleanFilter(
        field_name='user',
        method='filter_blacklist',
        widget=BooleanWidget(),
        help_text="""If True, it will get only the changesets created by the
            users that you blacklisted.""")
    mapping_teams = filters.CharFilter(
        field_name='user',
        method='filter_mapping_team',
        help_text="""Filter changesets created by users that are on a Mapping
            Team. It accepts a list of teams separated by commas.""")
    exclude_teams = filters.CharFilter(
        field_name='user',
        method='exclude_mapping_team',
        help_text="""Exclude changesets created by users that are on a Mapping
            Team. It accepts a list of teams separated by commas.""")
    exclude_trusted_teams = filters.BooleanFilter(
        field_name='user',
        method='filter_hide_trusted_teams',
        widget=BooleanWidget(),
        help_text="""If True, it will exclude the changesets created by the
            users that are part of trusted teams.""")
    area_lt = filters.CharFilter(
        field_name='user',
        method='filter_area_lt',
        help_text="""Filter changesets that have a bbox area lower than X times
            the area of your geospatial filter. For example, if the bbox or
            geometry you defined in your filter has an area of 1 degree and you
            set 'area_lt=2', it will filter the changesets whose bbox area is
            lower than 2 degrees.""")
    create__gte = filters.NumberFilter(
        field_name='create',
        lookup_expr='gte',
        help_text="""Filter changesets whose number of elements created are
            greater than or equal to a number.""")
    create__lte = filters.NumberFilter(
        field_name='create',
        lookup_expr='lte',
        help_text="""Filter changesets whose number of elements created are
            lower than or equal to a number.""")
    modify__gte = filters.NumberFilter(
        field_name='modify',
        lookup_expr='gte',
        help_text="""Filter changesets whose number of elements modified are
            greater than or equal to a number.""")
    modify__lte = filters.NumberFilter(
        field_name='modify',
        lookup_expr='lte',
        help_text="""Filter changesets whose number of elements modified are
            lower than or equal to a number.""")
    delete__gte = filters.NumberFilter(
        field_name='delete',
        lookup_expr='gte',
        help_text="""Filter changesets whose number of elements deleted are
            greater than or equal to a number.""")
    delete__lte = filters.NumberFilter(
        field_name='delete',
        lookup_expr='lte',
        help_text="""Filter changesets whose number of elements deleted are
            lower than or equal to a number.""")
    date__gte = filters.DateTimeFilter(
        field_name='date',
        lookup_expr='gte',
        help_text="""Filter changesets whose date is greater than or equal to a
            date or a datetime value.""")
    date__lte = filters.DateTimeFilter(
        field_name='date',
        lookup_expr='lte',
        help_text="""Filter changesets whose date is lower than or equal to a
            date or a datetime value.""")
    check_date__gte = filters.DateTimeFilter(
        field_name='check_date',
        lookup_expr='gte',
        help_text="""Filter changesets whose check_date is greater than or equal
            to a date or a datetime value.""")
    check_date__lte = filters.DateTimeFilter(
        field_name='check_date',
        lookup_expr='lte',
        help_text="""Filter changesets whose check_date is lower than or equal
            to a date or a datetime value.""")
    editor = filters.CharFilter(
        field_name='editor',
        lookup_expr='icontains',
        help_text="""Filter changesets created with a software editor. It uses
            the icontains lookup expression, so a query for 'josm' will return
            changesets created or last modified with all JOSM versions.""")
    comment = filters.CharFilter(
        field_name='comment',
        lookup_expr='icontains',
        help_text="""Filter changesets by its comment field using the icontains
            lookup expression.""")
    source = filters.CharFilter(
        field_name='source',
        lookup_expr='icontains',
        help_text="""Filter changesets by its source field using the icontains
            lookup expression.""")
    imagery_used = filters.CharFilter(
        field_name='imagery_used',
        lookup_expr='icontains',
        help_text="""Filter changesets by its imagery_used field using the
            icontains lookup expression.""")
    reasons = filters.CharFilter(
        field_name='reasons',
        method='filter_any_reasons',
        help_text="""Filter changesets that have one or more of the Suspicion
            Reasons. Inform the Suspicion Reasons ids separated by commas.""")
    all_reasons = filters.CharFilter(
        field_name='reasons',
        method='filter_all_reasons',
        help_text="""Filter changesets that have ALL the Suspicion Reasons of a
            list. Inform the Suspicion Reasons ids separated by commas.""")
    number_reasons__gte = filters.NumberFilter(
        field_name='number_reasons',
        method='filter_number_reasons',
        help_text="""Filter changesets whose number of Suspicion Reasons is
            equal or greater than a value.""")
    tags = filters.CharFilter(
        field_name='tags',
        method='filter_any_reasons',
        help_text="""Filter changesets that have one or more of the Tags. Inform
            the Tags ids separated by commas.""")
    all_tags = filters.CharFilter(
        field_name='tags',
        method='filter_all_reasons',
        help_text="""Filter changesets that have ALL the Tags of a list. Inform
            the Tags ids separated by commas.""")

    def filter_whitelist(self, queryset, name, value):
        if (self.request is None
                or self.request.user.is_authenticated) and value:
            whitelist = self.request.user.whitelists.values_list(
                'whitelist_user', flat=True)
            return queryset.exclude(user__in=whitelist)
        else:
            return queryset

    def filter_blacklist(self, queryset, name, value):
        if (self.request is None
                or self.request.user.is_authenticated) and value:
            blacklist = self.request.user.blacklisteduser_set.values_list(
                'uid', flat=True)
            return queryset.filter(uid__in=blacklist)
        else:
            return queryset

    def get_username_from_teams(self, teams):
        users = []
        for i in teams.values_list('users', flat=True):
            values = i
            if type(values) in [str, bytes, bytearray]:
                values = json.loads(values)
            for e in values:
                users.append(e.get('username'))
        return users

    def filter_mapping_team(self, queryset, name, value):
        try:
            # added `if team` to avoid empty strings
            teams = MappingTeam.objects.filter(
                name__in=[team.strip() for team in value.split(',') if team])
            users = self.get_username_from_teams(teams)
            return queryset.filter(user__in=users)
        except MappingTeam.DoesNotExist:
            return queryset

    def exclude_mapping_team(self, queryset, name, value):
        try:
            teams = MappingTeam.objects.filter(
                name__in=[team.strip() for team in value.split(',') if team])
            users = self.get_username_from_teams(teams)
            return queryset.exclude(user__in=users)
        except MappingTeam.DoesNotExist:
            return queryset

    def filter_hide_trusted_teams(self, queryset, name, value):
        teams = MappingTeam.objects.filter(trusted=True)
        users = self.get_username_from_teams(teams)
        if users:
            return queryset.exclude(user__in=users)
        else:
            return queryset

    def filter_checked_by(self, queryset, name, value):
        if (self.request is None
                or self.request.user.is_authenticated) and value:
            lookup = '__'.join([name, 'name__in'])
            users = [t.strip() for t in value.split(',')]
            return queryset.filter(**{lookup: users})
        else:
            return queryset

    def filter_users(self, queryset, name, value):
        if (self.request is None
                or self.request.user.is_authenticated) and value:
            lookup = '__'.join([name, 'in'])
            users_array = [t.strip() for t in value.split(',')]
            return queryset.filter(**{lookup: users_array})
        else:
            return queryset

    def filter_ids(self, queryset, name, value):
        lookup = '__'.join([name, 'in'])
        values = [int(n) for n in value.split(',')]
        return queryset.filter(**{lookup: values})

    def filter_uids(self, queryset, name, value):
        if (self.request is None
                or self.request.user.is_authenticated) and value:
            lookup = '__'.join([name, 'in'])
            values = [n for n in value.split(',')]
            return queryset.filter(**{lookup: values})
        else:
            return queryset

    def filter_any_reasons(self, queryset, name, value):
        lookup = '__'.join([name, 'id', 'in'])
        values = [int(t) for t in value.split(',')]
        return queryset.filter(**{lookup: values}).distinct()

    def filter_all_reasons(self, queryset, name, value):
        lookup = '__'.join([name, 'id'])
        values = [int(t) for t in value.split(',')]
        for term in values:
            queryset = queryset.filter(**{lookup: term})
        return queryset

    def filter_number_reasons(self, queryset, name, value):
        lookup = '__'.join([name, 'gte'])
        queryset = queryset.annotate(number_reasons=Count('reasons'))
        return queryset.filter(**{lookup: value})

    def order_queryset(self, queryset, name, value):
        allowed_fields = [
            'date', '-date', 'id', 'check_date', '-check_date', 'create',
            'modify', 'delete', '-create', '-modify', '-delete',
            'number_reasons', '-number_reasons'
        ]
        if value in allowed_fields:
            if value in ['number_reasons', '-number_reasons']:
                queryset = queryset.annotate(number_reasons=Count('reasons'))
            return queryset.order_by(value)
        else:
            return queryset

    def filter_area_lt(self, queryset, name, value):
        """This filter method was designed to exclude changesets that are much
        bigger than the filter area. For example, if you want to exclude
        changesets that are greater than 5 times the filter area, you need to
        set the value to 5.
        """
        if 'geometry' in self.data.keys():
            try:
                filter_area = self.data['geometry'].area
            except AttributeError:
                filter_area = GeometryField().to_internal_value(
                    self.data['geometry']).area
            return queryset.filter(area__lt=float(value) * filter_area)
        elif 'in_bbox' in self.data.keys():
            try:
                filter_area = Polygon.from_bbox(
                    (float(n) for n in self.data['in_bbox'].split(','))).area
                return queryset.filter(area__lt=float(value) * filter_area)
            except ValueError:
                return queryset
        else:
            return queryset

    class Meta:
        model = Changeset
        fields = ['geometry', 'users', 'area_lt']
Ejemplo n.º 30
0
class ActivityFilter(TogetherFilterSet):

    activity_id = CommaSeparatedCharFilter(name='id', lookup_expr='in')

    iati_identifier = CommaSeparatedCharFilter(name='iati_identifier',
                                               lookup_expr='in')

    activity_scope = CommaSeparatedCharFilter(
        name='scope__code',
        lookup_expr='in',
    )

    budget_not_provided = CommaSeparatedCharFilter(
        name='budget_not_provided',
        lookup_expr='in',
    )

    is_secondary_reporter = BooleanFilter(
        name='reporting_organisations__secondary_reporter',
        widget=BooleanWidget())

    has_crs_add = IsNullBooleanFilter(name='crsadd',
                                      lookup_expr='isnull',
                                      distinct=True,
                                      widget=BooleanWidget())

    has_other_identifier = IsNullBooleanFilter(name='otheridentifier',
                                               lookup_expr='isnull',
                                               distinct=True,
                                               widget=BooleanWidget())

    has_contact_info = IsNullBooleanFilter(name='contactinfo',
                                           lookup_expr='isnull',
                                           distinct=True,
                                           widget=BooleanWidget())

    has_activity_scope = IsNullBooleanFilter(name='scope',
                                             lookup_expr='isnull',
                                             distinct=True,
                                             widget=BooleanWidget())

    has_recipient_country = IsNullBooleanFilter(
        name='activityrecipientcountry',
        lookup_expr='isnull',
        distinct=True,
        widget=BooleanWidget())

    has_recipient_region = IsNullBooleanFilter(name='activityrecipientregion',
                                               lookup_expr='isnull',
                                               distinct=True,
                                               widget=BooleanWidget())

    has_location = IsNullBooleanFilter(name='location',
                                       lookup_expr='isnull',
                                       distinct=True,
                                       widget=BooleanWidget())

    has_sector = IsNullBooleanFilter(name='activitysector',
                                     lookup_expr='isnull',
                                     distinct=True,
                                     widget=BooleanWidget())

    has_tag = IsNullBooleanFilter(name='activitytag',
                                  lookup_expr='isnull',
                                  distinct=True,
                                  widget=BooleanWidget())

    has_country_budget_item = IsNullBooleanFilter(name='country_budget_items',
                                                  lookup_expr='isnull',
                                                  distinct=True,
                                                  widget=BooleanWidget())

    has_humanitarian_scope = IsNullBooleanFilter(name='humanitarianscope',
                                                 lookup_expr='isnull',
                                                 distinct=True,
                                                 widget=BooleanWidget())

    has_policy_marker = IsNullBooleanFilter(name='activitypolicymarker',
                                            lookup_expr='isnull',
                                            distinct=True,
                                            widget=BooleanWidget())

    has_collaboration_type = IsNullBooleanFilter(name='collaboration_type',
                                                 lookup_expr='isnull',
                                                 distinct=True,
                                                 widget=BooleanWidget())

    has_default_flow_type = IsNullBooleanFilter(name='default_flow_type',
                                                lookup_expr='isnull',
                                                distinct=True,
                                                widget=BooleanWidget())

    has_default_finance_type = IsNullBooleanFilter(name='default_finance_type',
                                                   lookup_expr='isnull',
                                                   distinct=True,
                                                   widget=BooleanWidget())

    has_default_aid_type = IsNullBooleanFilter(name='default_aid_types',
                                               lookup_expr='isnull',
                                               distinct=True,
                                               widget=BooleanWidget())

    has_default_tied_status = IsNullBooleanFilter(name='default_tied_status',
                                                  lookup_expr='isnull',
                                                  distinct=True,
                                                  widget=BooleanWidget())

    has_budget = IsNullBooleanFilter(name='budget',
                                     lookup_expr='isnull',
                                     distinct=True,
                                     widget=BooleanWidget())

    has_planned_disbursement = IsNullBooleanFilter(name='planneddisbursement',
                                                   lookup_expr='isnull',
                                                   distinct=True,
                                                   widget=BooleanWidget())

    has_capital_spend = IsNullBooleanFilter(name='capital_spend',
                                            lookup_expr='isnull',
                                            distinct=True,
                                            widget=BooleanWidget())

    has_document_link = IsNullBooleanFilter(name='documentlink',
                                            lookup_expr='isnull',
                                            distinct=True,
                                            widget=BooleanWidget())

    has_related_activity = IsNullBooleanFilter(name='relatedactivity',
                                               lookup_expr='isnull',
                                               distinct=True,
                                               widget=BooleanWidget())

    has_legacy_data = IsNullBooleanFilter(name='legacydata',
                                          lookup_expr='isnull',
                                          distinct=True,
                                          widget=BooleanWidget())

    has_condition = IsNullBooleanFilter(
        name='conditions',
        lookup_expr=
        'isnull',  # related name of Foreign Key for `activity` is `conditions` # NOQA: E501
        distinct=True,
        widget=BooleanWidget())
    has_result = IsNullBooleanFilter(name='result',
                                     lookup_expr='isnull',
                                     distinct=True,
                                     widget=BooleanWidget())

    has_fss = IsNullBooleanFilter(name='fss',
                                  lookup_expr='isnull',
                                  distinct=True,
                                  widget=BooleanWidget())

    document_link_category = ToManyFilter(
        qs=DocumentLink,
        lookup_expr='in',
        name='categories',
        fk='activity',
    )

    last_updated_datetime_gt = DateTimeFilter(lookup_expr='gt',
                                              name='last_updated_datetime')

    planned_start_date_lte = DateFilter(lookup_expr='lte',
                                        name='planned_start')

    planned_start_date_gte = DateFilter(lookup_expr='gte',
                                        name='planned_start')

    actual_start_date_lte = DateFilter(lookup_expr='lte', name='actual_start')

    actual_start_date_gte = DateFilter(lookup_expr='gte', name='actual_start')

    planned_end_date_lte = DateFilter(lookup_expr='lte', name='planned_end')

    planned_end_date_gte = DateFilter(lookup_expr='gte', name='planned_end')

    actual_end_date_lte = DateFilter(lookup_expr='lte', name='actual_end')

    actual_end_date_gte = DateFilter(lookup_expr='gte', name='actual_end')

    end_date_lte = DateFilter(lookup_expr='lte', name='end_date')

    end_date_gte = DateFilter(lookup_expr='gte', name='end_date')

    start_date_lte = DateFilter(lookup_expr='lte', name='start_date')

    start_date_gte = DateFilter(lookup_expr='gte', name='start_date')

    end_date_isnull = BooleanFilter(lookup_expr='isnull', name='end_date')
    start_date_isnull = BooleanFilter(lookup_expr='isnull', name='start_date')

    activity_status = CommaSeparatedCharFilter(
        lookup_expr='in',
        name='activity_status',
    )

    hierarchy = CommaSeparatedCharFilter(
        lookup_expr='in',
        name='hierarchy',
    )

    collaboration_type = CommaSeparatedCharFilter(
        lookup_expr='in',
        name='collaboration_type',
    )

    default_flow_type = CommaSeparatedCharFilter(
        lookup_expr='in',
        name='default_flow_type',
    )

    default_aid_type = CommaSeparatedCharFilter(
        lookup_expr='in',
        name='default_aid_types__aid_type__code',
    )

    default_finance_type = CommaSeparatedCharFilter(
        lookup_expr='in',
        name='default_finance_type',
    )

    default_tied_status = CommaSeparatedCharFilter(
        lookup_expr='in',
        name='default_tied_status',
    )

    budget_period_start = DateFilter(
        lookup_expr='gte',
        name='budget__period_start',
    )

    budget_period_end = DateFilter(lookup_expr='lte',
                                   name='budget__period_end')

    humanitarian = TypedChoiceFilter(choices=(('0', 'False'), ('1', 'True')),
                                     coerce=strtobool)

    humanitarian_scope_type = ToManyFilter(
        qs=HumanitarianScope,
        lookup_expr='in',
        name='type__code',
        fk='activity',
    )

    related_activity_id = ToManyFilter(
        qs=RelatedActivity,
        fk='current_activity',
        lookup_expr='in',
        name='ref_activity__normalized_iati_identifier',
    )

    related_activity_type = ToManyFilter(
        qs=RelatedActivity,
        lookup_expr='in',
        name='type__code',
        fk='current_activity',
    )

    related_activity_type_not = CommaSeparatedCharFilter(
        lookup_expr='in', name='relatedactivity__type__code', exclude=True)

    related_activity_transaction_receiver_organisation_name = ToManyFilter(
        qs=RelatedActivity,
        lookup_expr='in',
        name=
        'ref_activity__transaction__receiver_organisation__narratives__content',  # NOQA: E501
        fk='current_activity',
    )

    related_activity_recipient_country = ToManyFilter(
        qs=RelatedActivity,
        lookup_expr='in',
        name='ref_activity__recipient_country',
        fk='current_activity',
    )

    related_activity_recipient_region = ToManyFilter(
        qs=RelatedActivity,
        lookup_expr='in',
        name='ref_activity__recipient_region',
        fk='current_activity',
    )

    related_activity_sector = ToManyFilter(
        qs=RelatedActivity,
        lookup_expr='in',
        name='ref_activity__sector',
        fk='current_activity',
    )

    related_activity_sector_category = ToManyFilter(
        qs=RelatedActivity,
        lookup_expr='in',
        name='ref_activity__sector__category',
        fk='current_activity',
    )

    budget_currency = ToManyFilter(
        qs=Budget,
        lookup_expr='in',
        name='currency__code',
        fk='activity',
    )

    recipient_country = ToManyFilter(
        qs=ActivityRecipientCountry,
        lookup_expr='in',
        name='country__code',
        fk='activity',
    )

    recipient_region = ToManyFilter(
        qs=ActivityRecipientRegion,
        lookup_expr='in',
        name='region__code',
        fk='activity',
    )

    recipient_region_not = ToManyNotInFilter(
        qs=ActivityRecipientRegion,
        lookup_expr='in',
        name='region__code',
        fk='activity',
    )

    sector = ToManyFilter(
        qs=ActivitySector,
        lookup_expr='in',
        name='sector__code',
        fk='activity',
    )

    sector_startswith = ToManyFilter(
        qs=ActivitySector,
        lookup_expr='startswith',
        name='sector__code',
        fk='activity',
    )

    sector_vocabulary = ToManyFilter(
        qs=ActivitySector,
        lookup_expr='in',
        name='vocabulary__code',
        fk='activity',
    )

    sector_category = ToManyFilter(
        qs=ActivitySector,
        lookup_expr='in',
        name='sector__category__code',
        fk='activity',
    )

    sector_startswith_in = StartsWithInCommaSeparatedCharFilter(
        lookup_expr='startswith',
        name='sector__code',
    )

    policy_marker = ToManyFilter(
        qs=ActivityPolicyMarker,
        lookup_expr='in',
        name='code',
        fk='activity',
    )

    participating_organisation = ToManyFilter(
        qs=ActivityParticipatingOrganisation,
        lookup_expr='in',
        name='normalized_ref',
        fk='activity',
    )

    participating_organisation_name = ToManyFilter(
        qs=ActivityParticipatingOrganisation,
        lookup_expr='in',
        name='primary_name',
        fk='activity',
    )

    participating_organisation_role = ToManyFilter(
        qs=ActivityParticipatingOrganisation,
        lookup_expr='in',
        name='role__code',
        fk='activity',
    )

    participating_organisation_type = ToManyFilter(
        qs=ActivityParticipatingOrganisation,
        lookup_expr='in',
        name='type__code',
        fk='activity',
    )

    reporting_organisation_identifier = ToManyFilter(
        qs=ActivityReportingOrganisation,
        lookup_expr='in',
        name='organisation__organisation_identifier',
        fk='activity',
    )

    reporting_organisation_type = ToManyFilter(
        qs=ActivityReportingOrganisation,
        lookup_expr='in',
        name='type',
        fk='activity')

    reporting_organisation_identifier_startswith = ToManyFilter(
        qs=ActivityReportingOrganisation,
        lookup_expr='startswith',
        name='organisation__organisation_identifier',
        fk='activity',
    )

    result_title = ToManyFilter(
        qs=Result,
        lookup_expr='in',
        name='resulttitle__narratives__content',
        fk='activity',
    )

    indicator_title = ToManyFilter(qs=ResultIndicatorTitle,
                                   lookup_expr='in',
                                   name='primary_name',
                                   fk='result_indicator__result__activity')

    indicator_period_end_year = ToManyFilter(
        qs=ResultIndicatorPeriod,
        lookup_expr='year',
        name='period_end',
        fk='result_indicator__result__activity')

    other_identifier = ToManyFilter(
        qs=OtherIdentifier,
        lookup_expr='in',
        name='identifier',
        fk='activity',
    )

    #
    # Publisher meta filters
    #
    dataset_id = ToManyFilter(qs=Dataset,
                              lookup_expr='in',
                              name='id',
                              fk='activity')

    dataset_iati_id = ToManyFilter(qs=Dataset,
                                   lookup_expr='in',
                                   name='iati_id',
                                   fk='activity')

    publisher_id = ToManyFilter(qs=Publisher,
                                lookup_expr='in',
                                name='id',
                                fk='activity')

    publisher_iati_id = ToManyFilter(qs=Publisher,
                                     lookup_expr='in',
                                     name='iati_id',
                                     fk='activity')

    publisher_organisation_identifier = ToManyFilter(qs=Publisher,
                                                     lookup_expr='in',
                                                     name='publisher_iati_id',
                                                     fk='activity')

    #
    # Transaction filters
    #

    transaction_type = ToManyFilter(
        qs=Transaction,
        lookup_expr='in',
        name='transaction_type',
        fk='activity',
    )

    provider_organisation_primary_name = ToManyFilter(
        qs=Transaction,
        lookup_expr='in',
        name='provider_organisation__primary_name',
        fk='activity',
    )

    receiver_organisation_primary_name = ToManyFilter(
        qs=Transaction,
        lookup_expr='in',
        name='receiver_organisation__primary_name',
        fk='activity',
    )

    transaction_provider_organisation = ToManyFilter(
        qs=Transaction,
        lookup_expr='in',
        name='provider_organisation__ref',
        fk='activity',
    )

    transaction_receiver_organisation = ToManyFilter(
        qs=Transaction,
        lookup_expr='in',
        name='receiver_organisation__ref',
        fk='activity',
    )

    transaction_provider_organisation_name = ToManyFilter(
        qs=Transaction,
        lookup_expr='in',
        name='provider_organisation__narratives__content',
        fk='activity',
    )

    transaction_receiver_organisation_name = ToManyFilter(
        qs=Transaction,
        lookup_expr='in',
        name='receiver_organisation__narratives__content',
        fk='activity',
    )

    transaction_provider_activity = ToManyFilter(
        qs=Transaction,
        lookup_expr='in',
        name='provider_organisation__provider_activity_ref',
        fk='activity',
    )

    transaction_receiver_activity = ToManyFilter(
        qs=Transaction,
        lookup_expr='in',
        name='receiver_organisation__receiver_activity_ref',
        fk='activity',
    )

    transaction_provider_activity_reporting_org = ToManyFilter(
        qs=Transaction,
        lookup_expr='in',
        name=
        'provider_organisation__provider_activity__reporting_organisations__ref',  # NOQA: E501
        fk='activity',
    )

    transaction_currency = ToManyFilter(
        qs=Transaction,
        lookup_expr='in',
        name='currency',
        fk='activity',
    )

    transaction_date_year = ToManyFilter(qs=Transaction,
                                         lookup_expr='year',
                                         name='transaction_date',
                                         fk='activity')

    #
    # Aggregated values filters
    #

    total_budget_lte = NumberFilter(lookup_expr='lte',
                                    name='activity_aggregation__budget_value')

    total_budget_gte = NumberFilter(lookup_expr='gte',
                                    name='activity_aggregation__budget_value')

    total_disbursement_lte = NumberFilter(
        lookup_expr='lte', name='activity_aggregation__disbursement_value')

    total_disbursement_gte = NumberFilter(
        lookup_expr='gte', name='activity_aggregation__disbursement_value')

    total_incoming_funds_lte = NumberFilter(
        lookup_expr='lte', name='activity_aggregation__incoming_funds_value')

    total_incoming_funds_gte = NumberFilter(
        lookup_expr='gte', name='activity_aggregation__incoming_funds_value')

    total_expenditure_lte = NumberFilter(
        lookup_expr='lte', name='activity_aggregation__expenditure_value')

    total_expenditure_gte = NumberFilter(
        lookup_expr='gte', name='activity_aggregation__expenditure_value')

    total_commitment_lte = NumberFilter(
        lookup_expr='lte', name='activity_aggregation__commitment_value')

    total_commitment_gte = NumberFilter(
        lookup_expr='gte', name='activity_aggregation__commitment_value')

    total_hierarchy_budget_lte = NumberFilter(
        lookup_expr='lte',
        name='activity_plus_child_aggregation__budget_value')

    total_hierarchy_budget_gte = NumberFilter(
        lookup_expr='gte',
        name='activity_plus_child_aggregation__budget_value')

    total_hierarchy_disbursement_lte = NumberFilter(
        lookup_expr='lte',
        name='activity_plus_child_aggregation__disbursement_value')

    total_hierarchy_disbursement_gte = NumberFilter(
        lookup_expr='gte',
        name='activity_plus_child_aggregation__disbursement_value')

    total_hierarchy_incoming_funds_lte = NumberFilter(
        lookup_expr='lte',
        name='activity_plus_child_aggregation__incoming_funds_value')

    total_hierarchy_incoming_funds_gte = NumberFilter(
        lookup_expr='gte',
        name='activity_plus_child_aggregation__incoming_funds_value')

    total_hierarchy_expenditure_lte = NumberFilter(
        lookup_expr='lte',
        name='activity_plus_child_aggregation__expenditure_value')

    total_hierarchy_expenditure_gte = NumberFilter(
        lookup_expr='gte',
        name='activity_plus_child_aggregation__expenditure_value')

    total_hierarchy_commitment_lte = NumberFilter(
        lookup_expr='lte',
        name='activity_plus_child_aggregation__commitment_value')

    total_hierarchy_commitment_gte = NumberFilter(
        lookup_expr='gte',
        name='activity_plus_child_aggregation__commitment_value')

    #
    # Related to publishing
    #
    def filter_ready_to_publish(self, queryset, name, value):
        return queryset.filter(Q(ready_to_publish=True))

    ready_to_publish = CharFilter(name='ready_to_publish',
                                  method='filter_ready_to_publish')

    def filter_modified_ready_to_publish(self, queryset, name, value):
        return queryset.filter(Q(modified=True) & Q(ready_to_publish=True))

    modified_ready_to_publish = CharFilter(
        method='filter_modified_ready_to_publish')

    def filter_modified(self, queryset, name, value):
        return queryset.filter(Q(modified=True))

    modified = CharFilter(method='filter_modified')

    def filter_published(self, queryset, name, value):
        if value == "true":
            return queryset.filter(Q(published=True))
        else:
            return queryset.filter(Q(published=False))

    published = CharFilter(method='filter_published')

    class Meta:
        model = Activity
        together_exclusive = [('budget_period_start', 'budget_period_end')]
        fields = '__all__'
Ejemplo n.º 31
0
class TaxonFilter(django_filters.FilterSet):
    """Filter for Taxon."""

    is_terminal_taxon = BooleanFilter(label="Terminal Taxon",
                                      widget=BooleanWidget(),
                                      method="filter_leaf_nodes")
    current = BooleanFilter(label="Taxonomic name is current",
                            widget=BooleanWidget())
    admin_areas = ModelMultipleChoiceFilter(
        label="DBCA Regions and Districts",
        queryset=Area.objects.filter(area_type__in=[
            Area.AREATYPE_DBCA_REGION, Area.AREATYPE_DBCA_DISTRICT
        ]).order_by("area_type", "name"),
        method='taxa_occurring_in_area')
    eoo = geo_models.PolygonField()
    aoo = CharFilter(
        label="Area of Occupancy (AOO) intersects",
        widget=LeafletWidget(),
        method="taxa_occurring_in_poly",
    )
    conservation_level = MultipleChoiceFilter(
        label="Conservation Level",
        choices=cons_models.ConservationCategory.LEVEL_CHOICES,
        method='taxon_conservation_level')
    categories = ModelMultipleChoiceFilter(
        label="Conservation Listing Categories",
        queryset=cons_models.ConservationCategory.objects.filter(
            conservation_list__scope_species=True).order_by(
                "conservation_list__code",
                "rank").prefetch_related("conservation_list"),
        method="taxa_with_conservation_criteria")

    class Meta:
        """Class opts."""

        model = Taxon
        fields = [
            "paraphyletic_groups", "admin_areas", "eoo", "aoo",
            "conservation_level", "categories", "taxonomic_name",
            "vernacular_names", "rank", "is_terminal_taxon", "current",
            "publication_status", "name_id", "field_code"
        ]
        filter_overrides = FILTER_OVERRIDES

    def filter_leaf_nodes(self, queryset, name, value):
        """Return terminal taxa (leaf nodes) if value is true."""
        return queryset.filter(children__isnull=value)

    def taxa_occurring_in_area(self, queryset, name, value):
        """Return Taxa occurring in the given list of ``Area`` instances.

        * The filter returns a list of Area objects as ``value``
        * We need to extract their PKs to create a queryset equivalent to
          the list of objects ``value``. Only querysets allow agggregation, not lists.
        * A search_area Multipolygon is collected from the geoms of Areas in ``value``
        * The Taxon PKs are calculated from occurrences (TaxonAreaEncounters)
          ``intersect``ing the search_area
        * The queryset is filtered by the list of Taxon PKs with occurrences
        """
        if value:
            area_pks = [area.pk for area in value]
            search_area = Area.objects.filter(pk__in=area_pks).aggregate(
                Collect('geom'))["geom__collect"]
            taxon_pks_in_area = set([
                x["taxon__pk"]
                for x in occ_models.TaxonAreaEncounter.objects.filter(
                    Q(point__intersects=search_area)
                    | Q(geom__intersects=search_area)).values("taxon__pk")
            ])
            return queryset.filter(pk__in=taxon_pks_in_area)
        else:
            return queryset

    def taxa_occurring_in_poly(self, queryset, name, value):
        """Return Taxa occurring in the given Area polygon.

        * The filter returns a ``value``
        * (magic) value becomes search area
        * The Taxon PKs are calculated from occurrences (TaxonAreaEncounters)
          ``intersect``ing the search_area
        * The queryset is filtered by the list of Taxon PKs with occurrences
        """
        if value:
            taxon_pks_in_area = set([
                x["taxon__pk"]
                for x in occ_models.TaxonAreaEncounter.objects.filter(
                    Q(point__intersects=value)
                    | Q(geom__intersects=value)).values("taxon__pk")
            ])
            return queryset.filter(pk__in=taxon_pks_in_area)
        else:
            return queryset

    def taxon_conservation_level(self, queryset, name, value):
        """Return Taxa matching a conservation level.

        * The filter returns a list of ConservationCategory levels as ``value``
        * The Taxon PKs are calculated from active, WA CommunityConservationListings
          with categories matching the level
        * The queryset is filtered by the list of Taxon PKs with
          active taxon listings in WA  matching the conservation level
        """
        if value:
            taxon_pks = set([
                x["taxon__pk"]
                for x in cons_models.TaxonConservationListing.objects.filter(
                    scope=cons_models.ConservationListing.
                    SCOPE_WESTERN_AUSTRALIA,
                    status=cons_models.ConservationListing.STATUS_EFFECTIVE,
                    category__level__in=value).values("taxon__pk")
            ])
            return queryset.filter(pk__in=taxon_pks)
        else:
            return queryset

    def taxa_with_conservation_criteria(self, queryset, name, value):
        """Return Taxa matching a conservation level.

        * The filter returns a list of ConservationCategories as ``value``
        * The Taxon PKs are calculated from TaxonConservationListings
          with categories matching the list of categories in ``value``
        * The queryset is filtered by the list of Taxon PKs
          matching the conservation level
        """
        if value:
            taxon_pks = set([
                x["taxon__pk"]
                for x in cons_models.TaxonConservationListing.objects.filter(
                    category__in=value).values("taxon__pk")
            ])
            return queryset.filter(pk__in=taxon_pks)
        else:
            return queryset
Ejemplo n.º 32
0
class FeatureFilter(GeoFilterSet):
    """Filter Feature model objects."""
    geometry = GeometryFilter(
        name='geometry',
        lookup_expr='intersects',
        help_text="""Geospatial filter of features whose geometry intersects with
            another geometry. You can use any geometry type in this filter.""")
    checked = filters.BooleanFilter(
        widget=BooleanWidget(),
        help_text="""Filter features that were checked or not. Use true/false or
            1/0 values.""")
    changeset_checked = filters.BooleanFilter(
        name='changeset__checked',
        widget=BooleanWidget(),
        help_text="""Filter features whose changeset is checked or not. Use
            true/false or 1/0 values.""")
    harmful = filters.BooleanFilter(
        widget=BooleanWidget(),
        help_text="""Filter features that were marked as harmful or not harmful.
            Use true/false or 1/0 values.""")
    users = filters.CharFilter(
        name='changeset__user',
        method='filter_changeset_users',
        help_text="""Filter features whose last edit was made by a user. Use
            commas to search for more than one username.""")
    uids = filters.CharFilter(
        name='changeset__uid',
        method='filter_changeset_uid',
        help_text="""Filter features whose last edit was made by a user. Use
            commas to search for more than one user uid. The uid is a unique
            identifier of a OSM user.""")
    checked_by = filters.CharFilter(
        name='check_user',
        method='filter_check_users',
        help_text="""Filter features that were checked by a user. Use commas to
            search for more than one user.""")
    order_by = filters.CharFilter(
        name=None,
        method='order_queryset',
        help_text="""Order the Features by one of the following fields: id,
            osm_id, changeset__date, changeset_id, check_date or number_reasons.
            Use a minus sign (-) before the field name to reverse the ordering.
            Default ordering is '-changeset_id'.""")
    changeset_ids = filters.CharFilter(
        name='changeset__id',
        method='filter_changeset_ids',
        help_text="""Filter features by its changeset id. Send the ids separated
            by commas.""")
    osm_version__gte = filters.NumberFilter(
        name='osm_version',
        lookup_expr='gte',
        help_text="""Filter items whose osm_version is greater than or equal to
            a number.""")
    osm_version__lte = filters.NumberFilter(
        name='osm_version',
        lookup_expr='lte',
        help_text="""Filter items whose osm_version is lower than or equal to a
            number.""")
    osm_type = filters.CharFilter(
        name='osm_type',
        lookup_expr='exact',
        help_text="""Filter features by its osm_type. The value options are node,
            way or relation.""")
    date__gte = filters.DateTimeFilter(
        name='changeset__date',
        lookup_expr='gte',
        help_text="""Filter features whose changeset date is greater than or
            equal to a date or a datetime.""")
    date__lte = filters.DateTimeFilter(
        name='changeset__date',
        lookup_expr='lte',
        help_text="""Filter features whose changeset date is lower than or equal
            to a date or a datetime.""")
    check_date__gte = filters.DateTimeFilter(
        name='check_date',
        lookup_expr='gte',
        help_text="""Filter features whose check_date is greater than or equal
            to a date or a datetime.""")
    check_date__lte = filters.DateTimeFilter(
        name='check_date',
        lookup_expr='lte',
        help_text="""Filter features whose check_date is lower than or equal to
            a date or a datetime.""")
    editor = filters.CharFilter(
        name='changeset__editor',
        lookup_expr='icontains',
        help_text="""Filter features that were created or last modified with a
            software editor. The lookup expression used is 'icontains', so a
            query for 'josm' will get features created or last modified with
            all JOSM versions.
            """)
    reasons = filters.CharFilter(
        name='reasons',
        method='filter_any_reasons',
        help_text="""Filter features that have one or more of the Suspicion
            Reasons. Inform the Suspicion Reasons ids separated by commas.""")
    all_reasons = filters.CharFilter(
        name='reasons',
        method='filter_all_reasons',
        help_text="""Filter features that have ALL the Suspicion Reasons of a
        list. Inform the Suspicion Reasons ids separated by commas.""")
    number_reasons__gte = filters.NumberFilter(
        name='number_reasons',
        method='filter_number_reasons',
        help_text="""Filter features whose number of Suspicion Reasons is
            equal or greater than a value.""")
    tags = filters.CharFilter(
        name='tags',
        method='filter_any_reasons',
        help_text="""Filter features that have one or more of the Tags. Inform
            the Tags ids separated by commas.""")
    all_tags = filters.CharFilter(
        name='tags',
        method='filter_all_reasons',
        help_text="""Filter features that have ALL the Tags of a list. Inform
            the Tags ids separated by commas.""")

    def filter_changeset_users(self, queryset, name, value):
        if (self.request is None
                or self.request.user.is_authenticated) and value:
            lookup = '__'.join([name, 'in'])
            users_array = [t.strip() for t in value.split(',')]
            return queryset.filter(**{lookup: users_array})
        else:
            return queryset

    def filter_changeset_uid(self, queryset, name, value):
        if (self.request is None
                or self.request.user.is_authenticated) and value:
            lookup = '__'.join([name, 'in'])
            uids_array = [t.strip() for t in value.split(',')]
            return queryset.filter(**{lookup: uids_array})
        else:
            return queryset

    def filter_check_users(self, queryset, name, value):
        if (self.request is None
                or self.request.user.is_authenticated) and value:
            lookup = '__'.join([name, 'name', 'in'])
            check_users_array = [t.strip() for t in value.split(',')]
            return queryset.filter(**{lookup: check_users_array})
        else:
            return queryset

    def filter_any_reasons(self, queryset, name, value):
        lookup = '__'.join([name, 'id', 'in'])
        values = [int(t) for t in value.split(',')]
        return queryset.filter(**{lookup: values}).distinct()

    def filter_all_reasons(self, queryset, name, value):
        lookup = '__'.join([name, 'id'])
        values = [int(t) for t in value.split(',')]
        for term in values:
            queryset = queryset.filter(**{lookup: term})
        return queryset

    def filter_number_reasons(self, queryset, name, value):
        lookup = '__'.join([name, 'gte'])
        queryset = queryset.annotate(number_reasons=Count('reasons'))
        return queryset.filter(**{lookup: value})

    def order_queryset(self, queryset, name, value):
        allowed_fields = [
            '-id', 'id', '-osm_id', 'osm_id', 'changeset__date',
            '-changeset__date', 'changeset_id', 'check_date', '-check_date',
            'number_reasons', '-number_reasons'
        ]
        if value in allowed_fields:
            if value in ['number_reasons', '-number_reasons']:
                queryset = queryset.annotate(number_reasons=Count('reasons'))
            return queryset.order_by(value)
        else:
            return queryset

    def filter_changeset_ids(self, queryset, name, value):
        lookup = '__'.join([name, 'in'])
        values = [int(t) for t in value.split(',')]
        return queryset.filter(**{lookup: values})

    class Meta:
        model = Feature
        fields = []