Ejemplo n.º 1
0
 def get_sub_childrens(cls, value: List[Union[str, int]], level=1):
     if value:
         filters = models.Q(id__in=list(value))
         for i in range(level - 1):
             filters |= models.Q(**{f"{'parent__'*i}parent__in": value})
         return cls.objects.filter(filters)
     return cls.objects.none()
Ejemplo n.º 2
0
    def filter(self, request, qs):
        qs = super(BoundaryListView, self).filter(request, qs)

        if 'intersects' in request.GET:
            try:
                (set_slug, slug) = request.GET['intersects'].split('/')
                shape = Boundary.objects.filter(
                    slug=slug, set=set_slug).values_list('shape', flat=True)[0]
            except IndexError:
                raise Http404
            except ValueError:
                raise BadRequest(_("Invalid value for intersects filter"))
            qs = qs.filter(
                models.Q(shape__covers=shape)
                | models.Q(shape__overlaps=shape))

        if 'touches' in request.GET:
            try:
                (set_slug, slug) = request.GET['touches'].split('/')
                shape = Boundary.objects.filter(
                    slug=slug, set=set_slug).values_list('shape', flat=True)[0]
            except IndexError:
                raise Http404
            except ValueError:
                raise BadRequest(_("Invalid value for touches filter"))
            qs = qs.filter(shape__touches=shape)

        if 'sets' in request.GET:
            set_slugs = request.GET['sets'].split(',')
            qs = qs.filter(set__in=set_slugs)

        return qs
Ejemplo n.º 3
0
 def get_accessible(cls, user=None):
     user = user or get_current_user()
     if user.is_authenticated():
         queryset = Map.objects.filter(
             models.Q(owner=user) | models.Q(editors=user))
     else:
         queryset = Map.objects.filter(share_status=Map.PUBLIC)
     return queryset
Ejemplo n.º 4
0
    def get_query_set(self):
        qs = super(ApprovedUserManager, self).get_query_set()
        qs = qs.exclude(
            models.Q(birthday=None)
            & models.Q(birthday__lt=datetime.date.today() -
                       relativedelta(years=self.model.AGE_MIN)))

        return qs
Ejemplo n.º 5
0
 def search(self, qs, query):
     if query:
         query = SearchQuery(query, config=SEARCH_LANG)
         qs = qs.filter(
             models.Q(search_vector=query) |
             models.Q(pharma_company__search_vector=query)
         )
     qs = self.add_annotations(qs)
     return qs
Ejemplo n.º 6
0
    def create_from_input(self, **kwargs):
        """
        Create an address with the given data, unless a duplicate existing
        address is found. Return a tuple of (created, addresses), where
        ``created`` is ``True`` if an address was newly created, and
        ``addresses`` is an iterable of exact-match addresses (will be length
        one if newly created).

        If the data is bad (e.g. unknown state) will raise ValidationError.

        """
        user = kwargs.pop("user", None)

        street = kwargs.get("street", None)
        city = kwargs.get("city", None)
        state = kwargs.get("state", None)

        if state is not None:
            state = kwargs["state"] = compact_whitespace(state.upper().strip())

        if street is not None:
            street = kwargs["input_street"] = clean_street(
                compact_whitespace(street.strip()).rstrip("."))
            del kwargs["street"]

        if city is not None:
            city = kwargs["city"] = compact_whitespace(city.strip())

        if None not in [street, city, state]:
            addresses = self.filter(
                (
                    models.Q(input_street=street) |
                    models.Q(street=street)
                    ) &
                models.Q(city=city) &
                models.Q(state=state)
                )
        else:
            addresses = None

        created = False
        if not addresses:
            if kwargs.get("pl"):
                kwargs["mapped_by"] = user
                kwargs["mapped_timestamp"] = datetime.now()
            obj = self.model(**kwargs)
            obj.full_clean()
            obj.save(user=user)

            created = True
            addresses = [obj]

        return (created, addresses)
Ejemplo n.º 7
0
    def create_keyword_condition(self, data):
        keyword_fields = self._meta.keyword_fields
        if not keyword_fields:
            return models.Q()

        value = data.get(self._meta.keyword_field_name, None)
        if not value:
            return models.Q()

        conditions = models.Q()
        for field_name in keyword_fields:
            conditions |= models.Q(**{field_name + '__icontains': value})
        return conditions
Ejemplo n.º 8
0
class ReportImage(models.Model):
    image = models.ImageField(upload_to='uploads/reportimgs/')
    thumbnail = ImageSpecField(source='image',
                               processors=[ResizeToFill(320, 240)],
                               format='JPEG',
                               options={'quality': 75})
    content_type = models.ForeignKey(
        ContentType,
        on_delete=models.CASCADE,
        limit_choices_to=models.Q(app_label='reports', model='report')
        | models.Q(app_label='reports', model='onlinereport'))
    object_id = models.PositiveIntegerField(null=True)
    content_object = GenericForeignKey('content_type', 'object_id')
Ejemplo n.º 9
0
class Content(models.Model):
    game = models.ForeignKey(Game,
                             on_delete=models.CASCADE,
                             related_name="contents")
    content_type = models.ForeignKey(
        ContentType,
        on_delete=models.CASCADE,
        related_name="content_of",
        limit_choices_to=models.Q(app_label='character')
        | models.Q(app_label='things'))
    content_id = models.PositiveIntegerField()
    content = GenericForeignKey('content_type', 'content_id')
    position = models.PointField(null=True, blank=True)
    created = models.DateTimeField(default=timezone.now)
Ejemplo n.º 10
0
 class Meta:
     unique_together = (
         ('feature', 'layer_extra_geom'),
     )
     indexes = [
         models.Index(fields=['layer_extra_geom', 'identifier']),
         GistIndex(name='feg_geom_gist_index', fields=['layer_extra_geom', 'geom']),
         GinIndex(name='feg_properties_gin_index', fields=['properties']),
     ]
     constraints = [
         # geometry should be valid
         models.CheckConstraint(check=models.Q(geom__isvalid=True), name='geom_extra_is_valid'),
         # geometry should not be empty
         models.CheckConstraint(check=models.Q(geom__isempty=False), name='geom_extra_is_empty')
     ]
Ejemplo n.º 11
0
    def Q_member(self, member):
        UserAuth = auth.get_user_model()
        if isinstance(member, UserAuth):
            member = member.profile
        profile_ids = [member.id] + [team['id'] for team in member.teams.values('id')]

        return models.Q(owner_id__in=profile_ids)
Ejemplo n.º 12
0
 def __init__(self, model, query=None, using=None):
     # the model needs to be defined so that we can construct our custom
     # query
     if query is None:
         query = GeoQuery(model)
         query.add_q(geo_models.Q(effective_to__isnull=True))
     return super(ActiveGeoQuerySet, self).__init__(model, query, using)
Ejemplo n.º 13
0
 def filter_by_index(self, key, *values):
     matches_any_values_clause = reduce(
         operator.or_,
         [models.Q(indexed_values__value=value) for value in values])
     return self\
         .filter(indexed_values__index__attr_name=key)\
         .filter(matches_any_values_clause)
Ejemplo n.º 14
0
 def statistics(self):
     queryset = self.viewpoints.annotate(
         missing=models.Count('pk', filter=models.Q(
             pictures__isnull=True
         )),
         pending=models.Count('pictures', filter=models.Q(
             pictures__state=STATES.DRAFT
         )),
         refused=models.Count('pictures', filter=models.Q(
             pictures__state=STATES.REFUSED
         )),
     ).values('missing', 'pending', 'refused')
     try:
         return queryset[0]
     except IndexError:
         return {'missing': 0, 'pending': 0, 'refused': 0}
Ejemplo n.º 15
0
 def with_stats(self):
     return self.annotate(
         viewpoints_total=models.Count("viewpoints", distinct=True),
         pictures_submited=models.Count(
             "pictures__pk",
             filter=models.Q(pictures__state=Picture.SUBMITTED),
             distinct=True,
         ),
         pictures_accepted=models.Count(
             "pictures__pk",
             filter=models.Q(pictures__state=Picture.ACCEPTED),
             distinct=True,
         ),
         pictures_missing=models.F("viewpoints_total")
         - models.F("pictures_submited")
         - models.F("pictures_accepted"),
     )
Ejemplo n.º 16
0
    def get_boundaries(self, sets=None):
        r = {'boundaries_concordance': [], 'boundaries_centroid': []}

        concordances = PostcodeConcordance.objects.filter(
            code=self.code).values_list('boundary', flat=True)

        if sets:
            concordances = [
                boundary for boundary in concordances
                if boundary.split('/')[0] in sets
            ]

        concordance_sets = set()

        if concordances:
            q = ((models.Q(set=concordance.split('/')[0])
                  & models.Q(slug=concordance.split('/')[1]))
                 for concordance in concordances)

            boundaries = Boundary.objects.filter(reduce(lambda a, b: a | b, q))
            boundaries = Boundary.prepare_queryset_for_get_dicts(boundaries)
            boundaries = Boundary.get_dicts(boundaries)

            r['boundaries_concordance'] = boundaries

            for boundary in boundaries:
                concordance_sets.add(boundary['related']['boundary_set_url'])

        if self.centroid:
            q = models.Q(shape__contains=self.centroid)

            if sets:
                q &= models.Q(set__in=sets)

            boundaries = Boundary.objects.filter(q)
            boundaries = Boundary.prepare_queryset_for_get_dicts(boundaries)
            boundaries = Boundary.get_dicts(boundaries)

            r['boundaries_centroid'] = [
                boundary for boundary in boundaries if boundary['related']
                ['boundary_set_url'] not in concordance_sets
            ]

        return r
Ejemplo n.º 17
0
    def filter_products(self, **kwargs):
        q = kwargs['query'].get('q')
        ql = kwargs['query'].get('l')
        qc = kwargs['query'].get('c')
        lat = kwargs['query'].get('lat')
        lon = kwargs['query'].get('lon')
        if lon and lat:
            location = Point(float(lon), float(lat), srid=4326)
        # import pdb; pdb.set_trace()
        data = self.filter(
            models.Q(name__icontains=q) | models.Q(description__icontains=q))

        if qc != 'all':
            return data.filter(category__slug=qc)
        if ql == 'nearby_store':
            return data.annotate(
                distance=Distance('location', location)).order_by('distance')
        else:
            return data
Ejemplo n.º 18
0
 class Meta:
     ordering = ['id']
     indexes = [
         models.Index(fields=['layer', ]),
         models.Index(fields=['updated_at', ]),
         models.Index(fields=['updated_at', 'layer', ]),
         models.Index(fields=['layer', 'identifier']),
         models.Index(fields=['id', 'layer', ]),
         models.Index(fields=['source', 'layer', ]),
         models.Index(fields=['target', 'layer', ]),
         models.Index(fields=['source', 'target', 'layer']),
         GistIndex(fields=['layer', 'geom']),
         GinIndex(name='properties_gin_index', fields=['properties']),
     ]
     constraints = [
         # geometry should be valid
         models.CheckConstraint(check=models.Q(geom__isvalid=True), name='geom_is_valid'),
         # geometry should not be empty
         models.CheckConstraint(check=models.Q(geom__isempty=False), name='geom_is_empty')
     ]
Ejemplo n.º 19
0
 def get_geography(self, date):
     if len(self.geographies.all()) == 0:
         return None
     elif len(self.geographies.all()) == 1:
         return self.geographies.all()[0]
     else:
         if date < self.start_date:
             raise ValueError(
                 "date %s is before organisation start_date (%s)" %
                 (date.isoformat(), self.start_date.isoformat()))
         if self.end_date and date > self.end_date:
             raise ValueError(
                 "date %s is after organisation end_date (%s)" %
                 (date.isoformat(), self.end_date.isoformat()))
         try:
             return self.geographies.get((models.Q(start_date__lte=date)
                                          | models.Q(start_date=None))
                                         & (models.Q(end_date__gte=date)
                                            | models.Q(end_date=None)))
         except OrganisationGeography.DoesNotExist:
             return None
Ejemplo n.º 20
0
class EquipmentTag(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    tag_category = models.IntegerField(
        choices=TagCategory.TAG_CATEGORY_CHOICES, default=TagCategory.TRAILER)
    tag_type = models.IntegerField(choices=TagType.TAG_TYPE_CHOICES,
                                   default=TagType.FLATBED)
    assignee_limit = models.Q(
        models.Q(app_label='shipments', model='shipment')
        | models.Q(app_label='shipments', model='genericuser'))
    assignee_content_type = models.ForeignKey(
        ContentType,
        limit_choices_to=assignee_limit,
        related_name='equipment_tag_assignee')
    assignee_id = models.PositiveIntegerField()
    assignee = GenericForeignKey('assignee_content_type', 'assignee_id')
    assigner = models.ForeignKey('GenericUser', null=True, blank=True)

    @property
    def tag_category_label(self):
        return filter(lambda x: x[0] == self.tag_category,
                      TagCategory.TAG_CATEGORY_CHOICES)[0][1]

    @property
    def tag_type_label(self):
        return filter(lambda x: x[0] == self.tag_type,
                      TagType.TAG_TYPE_CHOICES)[0][1]

    class Meta:
        ordering = ('tag_category', )
        unique_together = (('assignee_id', 'assignee_content_type', 'tag_type',
                            'tag_category'), )

    def clean(self):
        ct = ContentType.objects.get(model=self.assignee_content_type)
        codename = 'change_%s' % ct.model
        if not self.assigner.user.has_perm(codename, self.assignee):
            raise ValidationError(
                _('Assigner must have permission to update assignee'))
Ejemplo n.º 21
0
 class Meta:
     verbose_name = "Time series"
     verbose_name_plural = "Time series"
     ordering = ("type",)
     unique_together = ["timeseries_group", "type", "time_step"]
     constraints = [
         models.UniqueConstraint(
             fields=["timeseries_group"],
             condition=models.Q(type=100),
             name="only_one_raw_timeseries_per_group",
         ),
         models.UniqueConstraint(
             fields=["timeseries_group"],
             condition=models.Q(type=200),
             name="only_one_checked_timeseries_per_group",
         ),
         models.UniqueConstraint(
             fields=["timeseries_group"],
             condition=models.Q(type=300),
             name="only_one_regularized_timeseries_per_group",
         ),
     ]
Ejemplo n.º 22
0
 class Meta:
     verbose_name = pgettext_lazy("Singular", "Time series")
     verbose_name_plural = pgettext_lazy("Plural", "Time series")
     ordering = ("type", )
     unique_together = ["timeseries_group", "type", "time_step"]
     constraints = [
         models.UniqueConstraint(
             fields=["timeseries_group"],
             condition=models.Q(type=100),
             name="only_one_initial_timeseries_per_group",
         ),
         models.UniqueConstraint(
             fields=["timeseries_group"],
             condition=models.Q(type=200),
             name="only_one_checked_timeseries_per_group",
         ),
         models.UniqueConstraint(
             fields=["timeseries_group"],
             condition=models.Q(type=300),
             name="only_one_regularized_timeseries_per_group",
         ),
     ]
Ejemplo n.º 23
0
    def anything(self, lookup_type, value, fields=anything_fields):
        queries = [
            models.Q(**{'%s__%s' % (field, lookup_type): value})
            for field in fields
        ]

        # Take one Q object from the list
        query = queries.pop()

        # Or the Q object with the ones remaining in the list
        for item in queries:
            query |= item

        return self.filter(query)
Ejemplo n.º 24
0
 def create_condition(self, field_name, lookup, value):
     if not value:
         return models.Q()
     key = field_name + '__' + lookup if lookup else field_name
     return models.Q(**{key: value})
Ejemplo n.º 25
0
 def get_for(user):
     return AdminLevel.objects.filter(
         models.Q(admin_level__region__public=True) |
         models.Q(admin_level__region__created_by=user) |
         models.Q(admin_level__region__project__members=user)
     ).distinct()
Ejemplo n.º 26
0
 def get_for(user):
     return Region.objects.filter(
         models.Q(public=True) |
         models.Q(created_by=user) |
         models.Q(project__members=user)
     ).distinct()
Ejemplo n.º 27
0
 def filter_by_id_or_slug(self, id_or_slug):
     return self.filter(models.Q(pk=id_or_slug) | models.Q(slug=id_or_slug))
Ejemplo n.º 28
0
 def get_by_id_or_slug(self, id_or_slug):
     return self.get(models.Q(pk=id_or_slug) | models.Q(slug=id_or_slug))
Ejemplo n.º 29
0
 class Meta:
     constraints = [
         models.CheckConstraint(
             name='%(app_label)s_%(class)s_file_source_value_matches_type',
             check=(
                 models.Q(
                     models.Q(type=FileSourceType.FILE_FIELD, file__regex=r'.+')
                     & models.Q(models.Q(url__in=['', None]) | models.Q(url__isnull=True))
                 )
                 | models.Q(
                     models.Q(type=FileSourceType.URL)
                     & models.Q(models.Q(url__isnull=False) & models.Q(url__regex=r'.+'))
                     & models.Q(models.Q(file__in=['', None]) | models.Q(file__isnull=True))
                 )
             ),
         )
     ]
Ejemplo n.º 30
0
 def filter_by_date(self, date):
     return self.filter(
         models.Q(divisionset__start_date__lte=date)
         & (models.Q(divisionset__end_date__gte=date)
            | models.Q(divisionset__end_date=None)))