当前位置: 首页>>代码示例>>Python>>正文


Python expressions.RawSQL方法代码示例

本文整理汇总了Python中django.db.models.expressions.RawSQL方法的典型用法代码示例。如果您正苦于以下问题:Python expressions.RawSQL方法的具体用法?Python expressions.RawSQL怎么用?Python expressions.RawSQL使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在django.db.models.expressions的用法示例。


在下文中一共展示了expressions.RawSQL方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: annotate_running_scans_count

# 需要导入模块: from django.db.models import expressions [as 别名]
# 或者: from django.db.models.expressions import RawSQL [as 别名]
def annotate_running_scans_count(self) -> 'ScanListQuerySet':
        return self.annotate(
            running_scans__count=RawSQL('''
                SELECT COUNT("{Scan}"."id")
                FROM "{Scan}"
                WHERE
                    "{Scan}"."end" IS NULL AND
                    "{Scan}"."site_id" IN
                        (SELECT "{Site_ScanLists}"."site_id"
                         FROM "{Site_ScanLists}"
                         WHERE "{Site_ScanLists}"."scanlist_id" = "{ScanList}"."id"
                         GROUP BY "{Site_ScanLists}"."site_id")
                '''.format(
                    Scan=Scan._meta.db_table,
                    Site_ScanLists=Site.scan_lists.through._meta.db_table,
                    ScanList=ScanList._meta.db_table), ())) 
开发者ID:PrivacyScore,项目名称:PrivacyScore,代码行数:18,代码来源:models.py

示例2: get_tag_order_by

# 需要导入模块: from django.db.models import expressions [as 别名]
# 或者: from django.db.models.expressions import RawSQL [as 别名]
def get_tag_order_by(self, tag):
        """Generate an OrderBy clause forcing JSON column->key to be used.

        This is only for helping to create a Window() for purposes of grouping
        by tag.

        Args:
            tag (str): The Django formatted tag string
                       Ex. pod_labels__key

        Returns:
            OrderBy: A Django OrderBy clause using raw SQL

        """
        descending = True if self.order_direction == "desc" else False
        tag_column, tag_value = tag.split("__")
        return OrderBy(RawSQL(f"{tag_column} -> %s", (tag_value,)), descending=descending) 
开发者ID:project-koku,项目名称:koku,代码行数:19,代码来源:queries.py

示例3: order_by_json_path

# 需要导入模块: from django.db.models import expressions [as 别名]
# 或者: from django.db.models.expressions import RawSQL [as 别名]
def order_by_json_path(self, json_path, language_code=None, order='asc'):
        """
        Orders a queryset by the value of the specified `json_path`.

        More about the `#>>` operator and the `json_path` arg syntax:
        https://www.postgresql.org/docs/current/static/functions-json.html

        More about Raw SQL expressions:
        https://docs.djangoproject.com/en/dev/ref/models/expressions/#raw-sql-expressions

        Usage example:
            MyModel.objects.language('en_us').filter(is_active=True).order_by_json_path('title')
        """
        language_code = (language_code
                            or self._language_code
                            or self.get_language_key(language_code))
        json_path = '{%s,%s}' % (language_code, json_path)
        # Our jsonb field is named `translations`.
        raw_sql_expression = RawSQL("translations#>>%s", (json_path,))
        if order == 'desc':
            raw_sql_expression = raw_sql_expression.desc()
        return self.order_by(raw_sql_expression) 
开发者ID:tatterdemalion,项目名称:django-nece,代码行数:24,代码来源:managers.py

示例4: get_recent_activity

# 需要导入模块: from django.db.models import expressions [as 别名]
# 或者: from django.db.models.expressions import RawSQL [as 别名]
def get_recent_activity():
        """
        Lists the 12 most recent actions by users.
        """
        # Here we must use raw sql because the ORM is not quite able to take
        # a queryset, look up two separate foreign keys in two separate models
        # to get an object from a fourth model and return that to filter the
        # first queryset.
        sql = (
            "select id from private_sharing_activityfeed where "
            + "(member_id, project_id) IN (select member_id, project_id "
            + "from private_sharing_datarequestprojectmember "
            + "where visible='true')"
        )
        project_qs = ActivityFeed.objects.filter(id__in=RawSQL(sql, "")).filter(
            member__user__is_active=True
        )
        non_project_qs = ActivityFeed.objects.filter(project__isnull=True).filter(
            member__user__is_active=True
        )
        recent_qs = non_project_qs | project_qs
        recent = recent_qs.order_by("-timestamp")[0:12]
        recent_1 = recent[:6]
        recent_2 = recent[6:]
        return (recent_1, recent_2) 
开发者ID:OpenHumans,项目名称:open-humans,代码行数:27,代码来源:views.py

示例5: order_by

# 需要导入模块: from django.db.models import expressions [as 别名]
# 或者: from django.db.models.expressions import RawSQL [as 别名]
def order_by(self, *field_names):
        if not self.json_field:
            raise ValueError(
                'json_field cannot be blank, please provide a field on which to perform the ordering'
            )

        def build_json_order_by(field):
            try:
                if field.replace('-', '') not in NAMED_BLOCKS:
                    return field
            except AttributeError:
                return field

            if field[0] == '-':
                descending = True
                field = field[1:]
            else:
                descending = False
            db_table = self.model._meta.db_table
            return OrderBy(RawSQL(f'LOWER({db_table}.{self.json_field}->>%s)', (field,)), descending=descending, nulls_last=True)

        field_ordering = [build_json_order_by(field) for field in field_names]
        return super().order_by(*field_ordering) 
开发者ID:OpenTechFund,项目名称:hypha,代码行数:25,代码来源:submissions.py

示例6: annotate_most_recent_scan_error_count

# 需要导入模块: from django.db.models import expressions [as 别名]
# 或者: from django.db.models.expressions import RawSQL [as 别名]
def annotate_most_recent_scan_error_count(self) -> 'ScanListQuerySet':
        return self.annotate(
            last_scan__error_count=RawSQL('''
                SELECT COUNT("id")
                FROM "{ScanError}"
                WHERE
                    "{ScanError}"."scan_id" = "{Site}"."last_scan_id"
                '''.format(
                    Scan=Scan._meta.db_table,
                    Site=Site._meta.db_table,
                    ScanError=ScanError._meta.db_table), ())) 
开发者ID:PrivacyScore,项目名称:PrivacyScore,代码行数:13,代码来源:models.py

示例7: annotate_most_recent_scan_start

# 需要导入模块: from django.db.models import expressions [as 别名]
# 或者: from django.db.models.expressions import RawSQL [as 别名]
def annotate_most_recent_scan_start(self) -> 'SiteQuerySet':
        return self.annotate(
            last_scan__start=RawSQL('''
                SELECT DISTINCT ON (site_id) "start"
                FROM "{Scan}"
                WHERE
                    site_id={Site}."id"
                ORDER BY "site_id", "end" DESC NULLS FIRST
                LIMIT 1
                '''.format(
                    Scan=Scan._meta.db_table,
                    Site=Site._meta.db_table,
                    Site_ScanLists=Site.scan_lists.through._meta.db_table), ())) 
开发者ID:PrivacyScore,项目名称:PrivacyScore,代码行数:15,代码来源:models.py

示例8: annotate_most_recent_scan_end_or_null

# 需要导入模块: from django.db.models import expressions [as 别名]
# 或者: from django.db.models.expressions import RawSQL [as 别名]
def annotate_most_recent_scan_end_or_null(self) -> 'SiteQuerySet':
        return self.annotate(
            last_scan__end_or_null=RawSQL('''
                SELECT DISTINCT ON (site_id) "end"
                FROM "{Scan}"
                WHERE
                    site_id={Site}."id"
                ORDER BY "site_id", "end" DESC NULLS FIRST
                LIMIT 1
                '''.format(
                    Scan=Scan._meta.db_table,
                    Site=Site._meta.db_table,
                    Site_ScanLists=Site.scan_lists.through._meta.db_table), ())) 
开发者ID:PrivacyScore,项目名称:PrivacyScore,代码行数:15,代码来源:models.py

示例9: annotate_most_recent_scan_result

# 需要导入模块: from django.db.models import expressions [as 别名]
# 或者: from django.db.models.expressions import RawSQL [as 别名]
def annotate_most_recent_scan_result(self) -> 'SiteQuerySet':
        return self.annotate(last_scan__result=RawSQL('''
        SELECT "{ScanResult}"."result"
        FROM "{ScanResult}"
        WHERE
            "{ScanResult}"."scan_id"="{Site}"."last_scan_id"
        LIMIT 1
        '''.format(
                ScanResult=ScanResult._meta.db_table,
                Site=Site._meta.db_table), ())) 
开发者ID:PrivacyScore,项目名称:PrivacyScore,代码行数:12,代码来源:models.py

示例10: erc20_tokens_with_balance

# 需要导入模块: from django.db.models import expressions [as 别名]
# 或者: from django.db.models.expressions import RawSQL [as 别名]
def erc20_tokens_with_balance(self, address: str) -> List[Dict[str, Any]]:
        """
        :return: List of dictionaries {'token_address': str, 'balance': int}
        """
        arguments_value_field = RawSQL("(arguments->>'value')::numeric", ())
        return self.erc20_events(
            address=address
        ).values('token_address').annotate(
            balance=Sum(Case(
                When(arguments__from=address, then=-arguments_value_field),
                default=arguments_value_field,
            ))
        ).order_by('-balance').values('token_address', 'balance') 
开发者ID:gnosis,项目名称:safe-relay-service,代码行数:15,代码来源:models.py

示例11: queryset

# 需要导入模块: from django.db.models import expressions [as 别名]
# 或者: from django.db.models.expressions import RawSQL [as 别名]
def queryset(self, request, queryset):
        if self.value() == 'FROM_SAFE_USER':
            param = 'from'
        elif self.value() == 'TO_SAFE_USER':
            param = 'to'
        else:
            return

        # Django doesn't support `->>` for auto conversion to text
        return queryset.annotate(address=RawSQL("arguments->>%s", (param,))
                                 ).filter(address__in=SafeContract.objects.values('address')) 
开发者ID:gnosis,项目名称:safe-relay-service,代码行数:13,代码来源:admin.py

示例12: test_raw_subquery

# 需要导入模块: from django.db.models import expressions [as 别名]
# 或者: from django.db.models.expressions import RawSQL [as 别名]
def test_raw_subquery(self):
        with self.assertNumQueries(0):
            raw_sql = RawSQL('SELECT id FROM auth_permission WHERE id = %s',
                             (self.t1__permission.pk,))
        qs = Test.objects.filter(permission=raw_sql)
        self.assert_tables(qs, Test, Permission)
        self.assert_query_cached(qs, [self.t1])

        qs = Test.objects.filter(
            pk__in=Test.objects.filter(permission=raw_sql))
        self.assert_tables(qs, Test, Permission)
        self.assert_query_cached(qs, [self.t1]) 
开发者ID:noripyt,项目名称:django-cachalot,代码行数:14,代码来源:read.py

示例13: test_invalidate_raw_subquery

# 需要导入模块: from django.db.models import expressions [as 别名]
# 或者: from django.db.models.expressions import RawSQL [as 别名]
def test_invalidate_raw_subquery(self):
        permission = Permission.objects.first()
        with self.assertNumQueries(0):
            raw_sql = RawSQL('SELECT id FROM auth_permission WHERE id = %s',
                             (permission.pk,))
        with self.assertNumQueries(1):
            data1 = list(Test.objects.filter(permission=raw_sql))
        self.assertListEqual(data1, [])

        test = Test.objects.create(name='test', permission=permission)

        with self.assertNumQueries(1):
            data2 = list(Test.objects.filter(permission=raw_sql))
        self.assertListEqual(data2, [test])

        permission.save()

        with self.assertNumQueries(1):
            data3 = list(Test.objects.filter(permission=raw_sql))
        self.assertListEqual(data3, [test])

        test.delete()

        with self.assertNumQueries(1):
            data4 = list(Test.objects.filter(permission=raw_sql))
        self.assertListEqual(data4, []) 
开发者ID:noripyt,项目名称:django-cachalot,代码行数:28,代码来源:write.py

示例14: test_invalidate_nested_raw_subquery

# 需要导入模块: from django.db.models import expressions [as 别名]
# 或者: from django.db.models.expressions import RawSQL [as 别名]
def test_invalidate_nested_raw_subquery(self):
        permission = Permission.objects.first()
        with self.assertNumQueries(0):
            raw_sql = RawSQL('SELECT id FROM auth_permission WHERE id = %s',
                             (permission.pk,))
        with self.assertNumQueries(1):
            data1 = list(Test.objects.filter(
                pk__in=Test.objects.filter(permission=raw_sql)))
        self.assertListEqual(data1, [])

        test = Test.objects.create(name='test', permission=permission)

        with self.assertNumQueries(1):
            data2 = list(Test.objects.filter(
                pk__in=Test.objects.filter(permission=raw_sql)))
        self.assertListEqual(data2, [test])

        permission.save()

        with self.assertNumQueries(1):
            data3 = list(Test.objects.filter(
                pk__in=Test.objects.filter(permission=raw_sql)))
        self.assertListEqual(data3, [test])

        test.delete()

        with self.assertNumQueries(1):
            data4 = list(Test.objects.filter(
                pk__in=Test.objects.filter(permission=raw_sql)))
        self.assertListEqual(data4, []) 
开发者ID:noripyt,项目名称:django-cachalot,代码行数:32,代码来源:write.py

示例15: RawSQLColumn

# 需要导入模块: from django.db.models import expressions [as 别名]
# 或者: from django.db.models.expressions import RawSQL [as 别名]
def RawSQLColumn(model, field=None):
    if isinstance(model, Field):
        field = model
        model = field.model
    if isinstance(field, six.string_types):
        field = model._meta.get_field(field)
    return RawSQL('%s.%s' % (model._meta.db_table, field.get_attname_column()[1]), ()) 
开发者ID:DMOJ,项目名称:online-judge,代码行数:9,代码来源:raw_sql.py


注:本文中的django.db.models.expressions.RawSQL方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。