示例#1
0
class PaperFilter(filters.FilterSet):

    doi = CharFilter(name='id_doi')
    pmi = CharFilter(name='id_pmi')
    arxiv = CharFilter(name='id_arx')
    pii = CharFilter(name='id_pii')
    title = CharFilter(name='title', lookup_expr='icontains')
    journal = MethodFilter()
    issn = MethodFilter()
    min_date = MethodFilter()
    max_date = MethodFilter()
    time_span = MethodFilter(distinct=True)

    class Meta:
        model = Paper
        fields = [
            'doi',
            'pmi',
            'arxiv',
            'pii',
            'title',
            'journal',
            'issn',
            'min_date',
            'max_date',
            'time_span',
        ]

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

    def filter_journal(self, queryset, value):
        return queryset.filter(
            Q(journal__title__icontains=value)
            | Q(journal__short_title__icontains=value))

    def filter_min_date(self, queryset, value):
        date = parse(value).date()
        return queryset.filter(date_co__gte=date)

    def filter_max_date(self, queryset, value):
        date = parse(value).date()
        return queryset.filter(date_co__lte=date)

    def filter_issn(self, queryset, value):
        return queryset.filter(
            Q(journal__id_issn=value) | Q(journal__id_eissn=value))

    def filter_time_span(self, queryset, value):
        value = int(value)
        date = (datetime.datetime.now() -
                datetime.timedelta(days=value)).date()
        return queryset.filter(date_co__gte=date)
示例#2
0
class _BaseComponentContactFilter(FilterSet):
    contact = MethodFilter(action='filter_by_contact', widget=SelectMultiple)
    email = MethodFilter(action='filter_by_email', widget=SelectMultiple)
    role = MultiValueFilter(name='role__name')
    component = MultiValueRegexFilter(name='component__name')

    @value_is_not_empty
    def filter_by_contact(self, qs, value):
        return _filter_contacts('username', 'mail_name', qs, value)

    @value_is_not_empty
    def filter_by_email(self, qs, value):
        return _filter_contacts('email', 'email', qs, value)
示例#3
0
class RepresentativeFilter(FilterSet):

    search = MethodFilter(action='search_filter')
    scoremin = MethodFilter(action='score_min_filter')
    scoremax = MethodFilter(action='score_max_filter')
    chamber = MethodFilter(action='chamber_filter')
    country = MethodFilter(action='group_filter')
    party = MethodFilter(action='group_filter')
    delegation = MethodFilter(action='group_filter')
    committee = MethodFilter(action='group_filter')

    class Meta:
        model = Representative
        fields = [
            'search', 'chamber', 'country', 'party', 'delegation', 'committee'
        ]

    def search_filter(self, qs, value):
        if len(value) == 0:
            return qs

        return qs.filter(slug__icontains=slugify(value))

    def chamber_filter(self, qs, value):
        if len(value) == 0:
            return qs

        today = datetime.date.today()
        return qs.filter(Q(mandates__end_date__gte=today)
                         | Q(mandates__end_date__isnull=True),
                         mandates__group__chamber=value)

    def group_filter(self, qs, value):
        if len(value) == 0:
            return qs

        today = datetime.date.today()
        return qs.filter(Q(mandates__end_date__gte=today)
                         | Q(mandates__end_date__isnull=True),
                         mandates__group=value)

    def score_min_filter(self, qs, value):
        if len(value) == 0:
            return qs

        try:
            return qs.filter(representative_score__score__gte=int(value))
        except ValueError:
            return qs

    def score_max_filter(self, qs, value):
        if len(value) == 0:
            return qs

        try:
            return qs.filter(representative_score__score__lte=int(value))
        except ValueError:
            return qs
示例#4
0
class FounderFilter(FilterSet):
    name = MethodFilter(action='filter_username', label=_('Search by name'))

    class Meta:
        model = Founder
        fields = ['expertise']

    def filter_username(self, queryset, value):
        if value:
            query = []

            value = re.sub("[^\w]", " ", value).split()
            for word in value:
                firstname = list(
                    queryset.filter(user__first_name__icontains=word).all())
                lastname = list(
                    queryset.filter(user__last_name__icontains=word).all())
                username = list(
                    queryset.filter(user__username__icontains=word).all())

                for user in firstname:
                    if user not in query:
                        query.append(user)
                for user in lastname:
                    if user not in query:
                        query.append(user)
                for user in username:
                    if user not in query:
                        query.append(user)

            return query

        else:
            return queryset
示例#5
0
class MentorFilter(FilterSet):
    name = MethodFilter(action='filter_username', label=_('Search by name'))
    type = ChoiceFilter(choices= FILTER_MENTOR_CHOICES )

    class Meta:
        model = Mentor
        fields = {'expertise' : ['exact'], 'type': ['exact']}

    def filter_username(self, queryset, value):
        if value:
            query = []

            value = re.sub("[^\w]", " ",  value).split()
            for word in value:
                firstname = list(queryset.filter(user__first_name__icontains = word).all())
                lastname = list(queryset.filter(user__last_name__icontains = word).all())
                username = list(queryset.filter(user__username__icontains = word).all())

                for user in firstname:
                    if user not in query:
                        query.append(user)
                for user in lastname:
                    if user not in query:
                        query.append(user)
                for user in username:
                    if user not in query:
                        query.append(user)

            return query

        else:
            return queryset
示例#6
0
class ReportFilter(FilterSet):
    center_point = MethodFilter(action='center_point')
    status_choices = (
        ('', '---------'),
        ('fixed', 'Fixed'),
        ('not-fixed', 'Not fixed'),
        ('in-progress', 'In progress'),
    )
    status = ChoiceFilter(choices=status_choices)
    from_date = DateTimeFilter(name='created_at', lookup_type='gte')
    to_date = DateTimeFilter(name='created_at', lookup_type='lte')
    from_date_unix = UnixTimeFilter(name='created_at', lookup_type='gte')
    to_date_unix = UnixTimeFilter(name='created_at', lookup_type='lte')
    order_by_field = 'order_by'
    city = ModelMultipleChoiceFilter(name='ward__city',
                                     queryset=City.objects.all(),
                                     widget=forms.CheckboxSelectMultiple())
    ward = ModelMultipleChoiceFilter(queryset=Ward.objects.all(),
                                     widget=forms.CheckboxSelectMultiple())

    class Meta:
        model = Report
        fields = [
            'ward', 'city', 'category', 'from_date', 'to_date',
            'from_date_unix', 'to_date_unix'
        ]
        order_by = (('-created_at', _('Latest First')), ('created_at',
                                                         _('Oldest First')))
示例#7
0
class AssignedFilter(FilterSet):
    """Filter to show assigned or unassigned mentions.

    Should were used pretty tools from  StatusModel manager, but
    would will use not good way for filtering. Bad 'choices' were defined
    in model.

    """
    # choices for Mentions statuses
    MENTIONS_CHOICES = (('all', 'All'), ('assigned', 'Assigned'),
                        ('unassigned', 'Unassigned'), ('flagged', 'Not Mine'))

    mention_status = MethodFilter(action='filter_status',
                                  widget=forms.widgets.Select(
                                      choices=MENTIONS_CHOICES,
                                      attrs={'class': 'form-control'}))

    class Meta:
        model = ToDo
        fields = ['mention_status']

    def filter_status(self, queryset, value):
        value = value.lower()

        if value == Mention.ASSIGNED.lower():
            return queryset.filter(status=Mention.ASSIGNED)
        if value == Mention.UNASSIGNED.lower():
            return queryset.exclude(
                status__in=[Mention.ASSIGNED, Mention.FLAGGED])
        if value == Mention.FLAGGED.lower():
            return queryset.filter(status=Mention.FLAGGED)

        return queryset
示例#8
0
class XtdCommentFilter(FilterSet):
    id_not = MethodFilter(action='filter_id')
    class Meta:
        model = XtdComment
        fields = ['object_pk', 'user', 'parent_id', 'id_not']

    def filter_id(self, queryset, value):
        return queryset.exclude(pk=value)
示例#9
0
class BaseFilterSet(FilterSet):
    pk__in = MethodFilter(action="handle_pk_in")

    def handle_pk_in(self, queryset, value):
        l = json.loads(value)
        if l:
            return queryset.filter(id__in=l)
        return queryset
示例#10
0
class ItemFilterSet(filters.FilterSet):

    related = MethodFilter()

    def filter_related(self, queryset, value):
        return queryset.filter(related__item=value)

    class Meta:
        model = models.Item
        fields = ('container', 'category')
示例#11
0
class SurveyFilter(filters.BaseFilterSet):
    no_responses_for = MethodFilter(action='exclude_response_user')

    class Meta:
        model = survey.SurveySerializer.Meta.model
        fields = [
            'no_responses_for', 'name', 'description', 'survey_type', 'owner'
        ]

    def exclude_response_user(self, queryset, value):
        return queryset.exclude(response__user_id=value)
示例#12
0
class DossierFilter(FilterSet):

    search = MethodFilter(action='search_filter')
    chamber = MethodFilter(action='chamber_filter')

    class Meta:
        model = Dossier
        fields = ['search', 'chamber']

    def search_filter(self, qs, value):
        if len(value) == 0:
            return qs

        return qs.filter(
            Q(title__icontains=value) | Q(reference__icontains=value)
            | Q(documents__link__icontains=value))

    def chamber_filter(self, qs, value):
        if len(value) == 0:
            return qs

        return qs.filter(documents__chamber=value)
示例#13
0
class ThemeFilter(FilterSet):

    search = MethodFilter(action='search_filter')

    class Meta:
        model = Theme
        fields = ['search']

    def search_filter(self, qs, value):
        if len(value) == 0:
            return qs

        return qs.filter(
            Q(name__icontains=value) | Q(description__icontains=value))
示例#14
0
class QuestionResponseFilter(filters.BaseFilterSet):
    null_answer = MethodFilter(action='handle_no_answer')

    class Meta:
        model = survey.QuestionResponseSerializer.Meta.model
        fields = [
            'survey', 'response', 'section', 'question', 'answer',
            'null_answer'
        ]

    def handle_no_answer(self, queryset, value):
        if value == False or value == 'False':
            return queryset.exclude(Q(answer__isnull=True) | Q(answer=''))
        else:
            return queryset.filter(Q(answer__isnull=True) | Q(answer=''))
示例#15
0
class QuestionChoiceFilter(filters.BaseFilterSet):
    question__in = MethodFilter(action="handle_question_in")

    class Meta:
        model = survey.QuestionChoiceSerializer.Meta.model
        fields = [
            'pk__in', 'question', 'question__in', 'name', 'value', 'help_text',
            'order', 'parent', 'section', 'owner'
        ]

    def handle_question_in(self, queryset, value):
        l = json.loads(value)
        if l:
            return queryset.filter(question__in=l)
        return queryset
示例#16
0
class QuestionResponseResourceFilter(filters.BaseFilterSet):
    question_response__in = MethodFilter(action="handle_question_response_in")

    class Meta:
        model = survey.QuestionResponseResourceSerializer.Meta.model
        fields = [
            'name', 'description', 'resource_type', 'content_type', 'size',
            'question_response', 'question_response__in', 'survey', 'response',
            'section', 'owner'
        ]

    def handle_question_response_in(self, queryset, value):
        l = json.loads(value)
        if l:
            return queryset.filter(question_response__in=l)
        return queryset
示例#17
0
class ProductFilterSet(FilterSet):
    """
    Filtering definitions for Product viewsets.

    Defined explicitly to provide non-trivial filtering functionalities.
    """
    not_in_quote = MethodFilter(action='filter_not_in_quote')

    class Meta:
        model = Product
        fields = [
            'model_number', 'serial_number', 'device_name', 'customer',
            'location', 'product_quotes__quote'
        ]

    def filter_not_in_quote(self, queryset, value):
        return queryset.exclude(product_quotes__quote__id=value)
示例#18
0
class LayerFilter(django_filters.FilterSet):
    tag = django_filters.CharFilter(name='layer_tags__name')
    username = django_filters.CharFilter(name='user__username')
    name_search = MethodFilter(action='name_tag_organization_filter')

    class Meta:
        model = Layer
        fields = ('username', 'name', 'organization', 'tag', 'created_at',
                  'capture_start', 'capture_end', 'area', 'srid')
        order_by = True

    def name_tag_organization_filter(self, queryset, value):
        layer_values = LayerTag.objects.filter(name__contains=value) \
                                       .values_list('layer_id', flat=True)

        return queryset.filter(
            Q(id__in=list(layer_values)) | Q(name__icontains=value)
            | Q(organization__icontains=value))
示例#19
0
class InsAdmEtpInitialFilter(filters.FilterSet):
    range = MethodFilter(action='range_filter')
    class Meta:
        model = InsAdmEtpInitial
        fields = [
            # COMPOSITE KEY
            'cod_anu',
            'cod_ind',
            'cod_etp',
            'cod_vrs_vet',
            'num_occ_iae',
            # others
            'cod_cge',
            'cod_dip',
        ]

    def range_filter(self, queryset, value):
        start, stop = value.split(':')
        return queryset[start:stop]
示例#20
0
class ReleaseComponentFilter(ComposeFilterSet):
    name = MultiValueFilter()
    release = MultiValueFilter(name='release__release_id')
    global_component = MultiValueFilter(name='global_component__name')
    bugzilla_component = MultiValueFilter(name='bugzilla_component__name')
    brew_package = MultiValueFilter()
    active = CaseInsensitiveBooleanFilter()
    type = CharFilter(name='type__name')
    dist_git_branch = MethodFilter(action='filter_by_dist_git_branch', widget=SelectMultiple)

    @value_is_not_empty
    def filter_by_dist_git_branch(self, qs, value):
        q = Q(dist_git_branch__in=value) | Q(release__releasedistgitmapping__dist_git_branch__in=value,
                                             dist_git_branch__isnull=True)
        return qs.filter(q)

    class Meta:
        model = ReleaseComponent
        fields = ('name', 'release', 'global_component', 'active',
                  'bugzilla_component', 'type', 'dist_git_branch')
示例#21
0
class WarcFilter(FilterSet):
    # Allows queries like /api/v1/warcs/?collection=39c00280274a4db0b1cb5bfa4d527a1e
    collection = CharFilter(
        name="harvest__historical_collection__collection_id")
    seed = ListFilter(name="harvest__historical_seeds__seed_id", distinct=True)
    harvest_date_start = IsoDateTimeFilter(name="harvest__date_started",
                                           lookup_type='gte')
    harvest_date_end = IsoDateTimeFilter(name="harvest__date_started",
                                         lookup_type='lte')
    exclude_web = MethodFilter(action="web_filter")

    class Meta:
        model = Warc
        fields = ['collection']

    @staticmethod
    def web_filter(queryset, value):
        if value.lower() in ("true", "yes"):
            return queryset.exclude(harvest__harvest_type='web')
        else:
            return queryset
示例#22
0
class ResolvedFilter(FilterSet):
    """Filter for TODOs by it's status.

    Model has Boolean field `is_closed` which we interpret as status of the
    TODO: resolved or unresolved.

    """
    STATUS_CHOICES = (
        ('all', 'All'),
        ('resolved', 'Resolved'),
        ('unresolved', 'Unresolved'),
    )

    status = MethodFilter(action='filter_status',
                          widget=forms.widgets.Select(
                              choices=STATUS_CHOICES,
                              attrs={'class': 'form-control'}))

    class Meta:
        model = ToDo
        fields = ['status']

    def filter_status(self, queryset, value):
        """Method for filtering TODOs by status.

        Args:
          queryset: QuerySet of TODOs
          value: value of the status (all, resolved or unresolved)

        Returns:
          QuerySet: filtered TODOs

        """
        if value == 'resolved':
            return queryset.filter(is_closed=True)
        if value == 'unresolved':
            return queryset.filter(is_closed=False)
        return queryset
示例#23
0
class MyPaperFilter(PaperFilter):

    added = MethodFilter()
    trashed = MethodFilter()
    pinned = MethodFilter()
    banned = MethodFilter()
    journal_id = ModelMultipleChoiceFilter(
        name='journal',
        queryset=Journal.objects.all(),
    )
    author_id = ModelMultipleChoiceFilter(
        name='authors',
        queryset=Author.objects.all(),
    )
    scored = MethodFilter()
    time_span = MethodFilter()

    class Meta:
        model = Paper
        fields = [
            'doi',
            'pmi',
            'arxiv',
            'pii',
            'title',
            'journal',
            'issn',
            'min_date',
            'max_date',
            'scored',
            'added',
            'trashed',
            'pinned',
            'banned',
            'journal_id',
            'author_id',
            'time_span',
        ]

    def __init__(self, *args, **kwargs):
        super(MyPaperFilter, self).__init__(*args, **kwargs)
        self.form.fields['journal_id'].always_filter = False
        self.form.fields['author_id'].always_filter = False

    def filter_time_span(self, queryset, value):
        return queryset

    def filter_added(self, queryset, value):
        if value in ['1', 'true']:
            query = Q(userlib_paper__userlib=self.request.user.id) & \
                    Q(paperuser__store=PAPER_ADDED) & \
                    Q(paperuser__user=self.request.user)
            return queryset.filter(query).order_by(
                '-userlib_paper__date_created')
        elif value in ['0', 'false']:
            query = Q(paperuser__user=self.request.user) & \
                Q(paperuser__store=PAPER_TRASHED)
            return queryset.filter(~query)

    def filter_trashed(self, queryset, value):
        query = Q(paperuser__user=self.request.user) & \
                Q(paperuser__store=PAPER_TRASHED)
        if value in ['1', 'true']:
            return queryset.filter(query)
        elif value in ['0', 'false']:
            return queryset.filter(~query)

    def filter_pinned(self, queryset, value):
        query = Q(paperuser__user=self.request.user) & \
                Q(paperuser__watch=PAPER_PINNED)
        if value in ['1', 'true']:
            return queryset.filter(query).order_by('-paperuser__modified')
        elif value in ['0', 'false']:
            return queryset.filter(~query)

    def filter_banned(self, queryset, value):
        query = Q(paperuser__user=self.request.user) & \
                Q(paperuser__watch=PAPER_BANNED)
        if value in ['1', 'true']:
            return queryset.filter(query)
        elif value in ['0', 'false']:
            return queryset.filter(~query)

    def filter_scored(self, queryset, value):
        if value in ['1', 'true']:
            type = self.data.get('type', 'stream')
            feed_name = self.data.get('feed', 'main')
            time_span = self.data.get('time_span',
                                      settings.FEED_TIME_SPAN_DEFAULT)
            cutoff_datetime = (datetime.datetime.now() -
                               datetime.timedelta(days=int(time_span))).date()
            if type == 'stream':
                return queryset.filter(
                    Q(streampapers__stream__name=feed_name)
                    & Q(streampapers__stream__user=self.request.user)
                    & Q(streampapers__date__gt=cutoff_datetime)).order_by(
                        '-streampapers__score')
            elif type == 'trend':
                return queryset.filter(
                    Q(trendpapers__trend__name=feed_name)
                    & Q(trendpapers__trend__user=self.request.user)
                    & Q(trendpapers__date__gt=cutoff_datetime)).order_by(
                        '-trendpapers__score')

        return queryset
示例#24
0
class MyThreadFilter(ThreadFilter):

    owned = MethodFilter()
    scored = MethodFilter(distinct=True)
    pinned = MethodFilter()
    banned = MethodFilter()
    joined = MethodFilter()
    left = MethodFilter()
    published = MethodFilter()
    invited = MethodFilter()
    invited_pending = MethodFilter()
    invited_accepted = MethodFilter()

    class Meta:
        model = Thread
        fields = [
            'doi',
            'pmi',
            'arx',
            'pii',
            'type',
            'privacy',
            'title',
            'author',
            'min_date',
            'max_date',
            'time_span',
            'owned',
            'scored',
            'pinned',
            'banned',
            'joined',
            'left',
            'published',
            'invited',
            'invited_pending',
            'invited_accepted',
        ]

    @property
    def qs(self):
        """To deal with ordering"""
        qs = super(MyThreadFilter, self).qs
        scored = self.data.get('scored', '0')
        pinned = self.data.get('pinned', '0')
        joined = self.data.get('joined', '0')
        if scored in ['1', 'true']:
            qs = qs.order_by('-threadfeedthreads__score', '-published_at')
        elif joined in ['1', 'true']:  # in my-library | papers
            qs = qs.order_by('-threaduser__modified')
        elif pinned in ['1', 'true']:  # in my-library | pinned
            qs = qs.order_by('-threaduser__modified')

        self._qs = qs
        return self._qs

    def filter_owned(self, queryset, value):
        if value in ['1', 'true']:
            return queryset.filter(user=self.request.user)
        elif value in ['0', 'false']:
            return queryset.filter(~Q(user=self.request.user))

    def filter_pinned(self, queryset, value):
        query = Q(threaduser__user=self.request.user) & \
                Q(threaduser__watch=THREAD_PINNED)
        if value in ['1', 'true']:
            return queryset.filter(query)
        elif value in ['0', 'false']:
            return queryset.filter(~query)

    def filter_banned(self, queryset, value):
        query = Q(threaduser__user=self.request.user) & \
                Q(threaduser__watch=THREAD_BANNED)
        if value in ['1', 'true']:
            return queryset.filter(query)
        elif value in ['0', 'false']:
            return queryset.filter(~query)

    def filter_joined(self, queryset, value):
        query = Q(threaduser__user=self.request.user) & \
                Q(threaduser__participate=THREAD_JOINED)
        if value in ['1', 'true']:
            return queryset.filter(query)
        elif value in ['0', 'false']:
            return queryset.filter(~query)

    def filter_left(self, queryset, value):
        query = Q(threaduser__user=self.request.user) & \
                Q(threaduser__participate=THREAD_LEFT)
        if value in ['1', 'true']:
            return queryset.filter(query)
        elif value in ['0', 'false']:
            return queryset.filter(~query)

    def filter_published(self, queryset, value):
        if value in ['1', 'true']:
            return queryset.filter(
                Q(user=self.request.user) & ~Q(published_at=None))
        elif value in ['0', 'false']:
            return queryset.filter(
                Q(user=self.request.user) & Q(published_at=None))

    def filter_invited(self, queryset, value):
        query = Q(threaduserinvite__to_user=self.request.user)
        if value in ['1', 'true']:
            return queryset.filter(query)
        elif value in ['0', 'false']:
            return queryset.filter(~query)

    def filter_invited_pending(self, queryset, value):
        query = Q(threaduserinvite__to_user=self.request.user) & \
                Q(threaduserinvite__status=THREAD_INVITE_PENDING)
        if value in ['1', 'true']:
            return queryset.filter(query)
        elif value in ['0', 'false']:
            return queryset.filter(~query)

    def filter_invited_accepted(self, queryset, value):
        query = Q(threaduserinvite__to_user=self.request.user) & \
                Q(threaduserinvite__status=THREAD_INVITE_ACCEPTED)
        if value in ['1', 'true']:
            return queryset.filter(query)
        elif value in ['0', 'false']:
            return queryset.filter(~query)

    def filter_scored(self, queryset, value):
        if value in ['1', 'true']:
            feed_name = self.data.get('feed', 'main')
            return queryset.filter(
                Q(threadfeedthreads__threadfeed__name=feed_name)
                & Q(threadfeedthreads__threadfeed__user=self.request.user))
        return queryset
示例#25
0
class ThreadFilter(filters.FilterSet):

    doi = CharFilter(name='paper__id_doi')
    pmi = CharFilter(name='paper__id_pmi')
    arx = CharFilter(name='paper__id_arx')
    pii = CharFilter(name='paper__id_pii')
    type = ChoiceFilter(choices=THREAD_TYPES)
    privacy = ChoiceFilter(choices=THREAD_PRIVACIES)
    private = MethodFilter()
    title = CharFilter(name='title', lookup_expr='icontains')
    author = MethodFilter()
    user_id = ModelMultipleChoiceFilter(
        name='user',
        queryset=User.objects.all(),
    )
    min_date = DateFilter(name='published_at', lookup_expr='gte')
    max_date = DateFilter(name='published_at', lookup_expr='lte')
    time_span = MethodFilter(distinct=True)
    third_party = MethodFilter()

    class Meta:
        model = Thread
        fields = [
            'doi',
            'pmi',
            'arx',
            'pii',
            'type',
            'privacy',
            'title',
            'author',
            'min_date',
            'max_date',
            'time_span',
        ]
        order_by = ['published_at']

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

    def filter_private(self, queryset, value):
        query = Q(privacy=THREAD_PRIVATE)
        if value in ['1', 'true']:
            return queryset.filter(query)
        elif value in ['0', 'false']:
            return queryset.filter(~query)

    # def filter_type(self, queryset, value):
    #     if value == THREAD_TYP:
    #         return queryset.filter(query)
    #     elif value in ['0',  'false']:
    #         return queryset.filter(~query)

    def filter_author(self, queryset, value):
        return queryset.filter(
            Q(user__first_name__icontains=value)
            | Q(user__last_name__icontains=value))

    def filter_time_span(self, queryset, value):
        value = int(value)
        date = (datetime.datetime.now() -
                datetime.timedelta(days=value)).date()
        return queryset.filter(published_at__gte=date)

    def filter_third_party(self, queryset, value):
        if value in ['0', 'false']:
            third_party_models = Thread.THIRD_PARTY_TYPES
            kwargs = dict((('{0}__isnull'.format(n.lower()), True)
                           for _, n in third_party_models))
            return queryset.filter(**kwargs)
        else:
            kwargs = {'{0}__isnull'.format(value): False}
            return queryset.filter(**kwargs)
示例#26
0
class PropertySearchFilter(django_filters.FilterSet):
    streetAddress = django_filters.CharFilter(lookup_type='icontains',
                                              label="Street address")
    parcel = django_filters.CharFilter(lookup_type='icontains',
                                       label="Parcel number")
    st = Property.objects.order_by('structureType').distinct(
        'structureType').values_list('structureType',
                                     flat=True).order_by('structureType')
    structure_types = zip(st, st)
    structureType = django_filters.MultipleChoiceFilter(
        choices=structure_types, name='structureType', label='Structure Type')

    status_choices = [('available', 'Available'),
                      ('review', 'Application under review'),
                      ('approved', 'Approved for Sale'), ('sold', 'Sold')]
    #status = django_filters.MultipleChoiceFilter(choices=status_choices, required=False, lookup_type='icontains')
    status = ChoiceMethodFilter(label='Status',
                                widget=forms.Select,
                                action='filter_status',
                                choices=status_choices)

    # structureType = django_filters.ModelMultipleChoiceFilter(
    # 	queryset=Property.objects.order_by('structureType').distinct('structureType').values('structureType'),
    # 	to_field_name="structureType",
    # 	label="Structure Type",
    # )

    #structureType = django_filters.ModelMultipleChoiceFilter(queryset=Property.objects.values_list('structureType', flat=True).distinct('structureType').order_by('structureType'), to_field_name="structureType", label="Structure Type")
    #zoning = django_filters.ModelMultipleChoiceFilter(queryset=Zoning.objects.values_list('name', flat=True).distinct('name').order_by('name'), to_field_name="name", label="Zoning")

    #zoning = forms.ModelMultipleChoiceField(queryset=Zoning.objects.all().order_by('name'), required=False)
    #zipcode = forms.ModelMultipleChoiceField(queryset=Zipcode.objects.all().order_by('name'), required=False)
    #cdc = forms.ModelMultipleChoiceField(queryset=CDC.objects.all().order_by('name'), required=False)

    searchArea = MethodFilter(action="filter_searchArea")

    class Meta:
        model = Property
        #fields = ['parcel', 'streetAddress', 'nsp', 'structureType', 'cdc', 'zone', 'sidelot_eligible', 'homestead_only', 'bep_demolition']
        form = PropertySearchForm

    def filter_status(self, queryset, value):
        if value == 'available':
            return queryset.filter(status__icontains='Available')
        if value == 'review':
            return queryset.filter(
                (Q(renew_owned__exact=False)
                 & Q(status__icontains='Sale approved by Board of Directors'))
                | Q(status__icontains='Sale approved by Review Committee'))
        if value == 'approved':
            return queryset.filter(
                (Q(renew_owned__exact=True)
                 & Q(status__icontains='Sale approved by Board of Directors'))
                | Q(status__icontains='Sale approved by MDC'))
        if value == 'sold':
            return queryset.filter(status__contains='Sold')

        return queryset

    def filter_searchArea(self, queryset, value):
        try:
            searchGeometry = GEOSGeometry(value, srid=900913)
        except Exception:
            return queryset

        return queryset.filter(geometry__within=searchGeometry)
示例#27
0
class TaskFilter(django_filters.FilterSet):

    RECORDS_TYPES = (
        ('', _('Todos')),
        ('modified', _('Modificados')),
        ('not_modified', _('No modificados')),
    )

    RECORD_STATUS = (
        ('', _('Todos')),
        ('translated', _('Traducidos')),
        ('not_translated', _('No traducidos'))
    )

    usuario = django_filters.ModelChoiceFilter(queryset=TransUser.objects.all(), required=False,
                                               label=_('Usuario'), name='user')

    content_type = django_filters.ChoiceFilter(choices=(), required=False, label=_('Clase'))

    language = django_filters.ModelChoiceFilter(queryset=TransLanguage.objects.order_by('name'), required=False,
                                                label=_('Idioma'))

    record_status = MethodFilter(label=_('Estado'), widget=Select(choices=RECORD_STATUS), required=False)

    record_types = MethodFilter(label=_('Tipo registro'), widget=Select(choices=RECORDS_TYPES))

    object_pk = django_filters.NumberFilter(required=False, label=_('Clave'))

    dates = django_filters.DateFromToRangeFilter(label=_('Rango de fechas'), required=False, name='date_modification')

    class Meta:
        model = TransTask
        fields = ('usuario', 'language', 'content_type', 'record_types', 'record_status', 'object_pk', 'dates')

    @staticmethod
    def filter_record_status(queryset, value):
        if value == 'translated':
            return queryset.extra(
                where=["object_field_value_translation IS NOT NULL AND object_field_value_translation !=''"]
            )
        elif value == 'not_translated':
            return queryset.extra(
                where=["object_field_value_translation IS NULL OR object_field_value_translation =''"]
            )
        return queryset

    @staticmethod
    def filter_record_types(queryset, value):
        if value == 'modified':
            return queryset.extra(
                where=["to_char(date_creation, 'YY-MM-DD HH24:MI')!=to_char(date_modification, 'YY-MM-DD HH24:MI')"]
            )
        elif value == 'not_modified':
            return queryset.extra(
                where=["to_char(date_creation, 'YY-MM-DD HH24:MI')=to_char(date_modification, 'YY-MM-DD HH24:MI')"]
            )
        return queryset

    @staticmethod
    def filter_object_field_label(queryset, value):
        if not value:
            return queryset
        obj_class, obj_field = value.split('__')
        return queryset.filter(object_class=obj_class, object_field=obj_field)

    def __init__(self, data=None, queryset=None, prefix=None, strict=None, user=None):
        super().__init__(data, queryset, prefix, strict)
        self.filters['content_type'].extra['choices'] = self.get_choices_for_models()

        if not user:
            return

        del self.filters['usuario']
        languages = user.languages.all()
        if languages:
            num = languages.count()
            if num > 1:
                self.filters['language'].extra['queryset'] = languages
            elif num == 1:
                del self.filters['language']

    @staticmethod
    def get_choices_for_models():
        """
        Get the select choices for models in optgroup mode
        :return:
        """
        result = {}

        apps = [item.model.split(' - ')[0] for item in TransModelLanguage.objects.all()]
        qs = ContentType.objects.exclude(model__contains='translation').filter(app_label__in=apps).order_by(
            'app_label', 'model'
        )
        for ct in qs:
            if not issubclass(ct.model_class(), TranslatableModel):
                continue
            if ct.app_label not in result:
                result[ct.app_label] = []
            result[ct.app_label].append((
                ct.id, str(ct.model_class()._meta.verbose_name_plural)
            ))
        choices = [(str(_('Todas las clases')), (('', _('Todas las clases')),))]
        for key, value in result.items():
            choices.append((key, tuple([it for it in sorted(value, key=lambda el: el[1])])))
        return choices