| 1913 | |
| 1914 | @deconstructible(path="django.db.models.OrderBy") |
| 1915 | class OrderBy(Expression): |
| 1916 | template = "%(expression)s %(ordering)s" |
| 1917 | conditional = False |
| 1918 | constraint_validation_compatible = False |
| 1919 | allows_composite_expressions = True |
| 1920 | |
| 1921 | def __init__(self, expression, descending=False, nulls_first=None, nulls_last=None): |
| 1922 | if nulls_first and nulls_last: |
| 1923 | raise ValueError("nulls_first and nulls_last are mutually exclusive") |
| 1924 | if nulls_first is False or nulls_last is False: |
| 1925 | raise ValueError("nulls_first and nulls_last values must be True or None.") |
| 1926 | self.nulls_first = nulls_first |
| 1927 | self.nulls_last = nulls_last |
| 1928 | self.descending = descending |
| 1929 | if not hasattr(expression, "resolve_expression"): |
| 1930 | raise ValueError("expression must be an expression type") |
| 1931 | self.expression = expression |
| 1932 | |
| 1933 | def __repr__(self): |
| 1934 | return "{}({}, descending={})".format( |
| 1935 | self.__class__.__name__, self.expression, self.descending |
| 1936 | ) |
| 1937 | |
| 1938 | def set_source_expressions(self, exprs): |
| 1939 | self.expression = exprs[0] |
| 1940 | |
| 1941 | def get_source_expressions(self): |
| 1942 | return [self.expression] |
| 1943 | |
| 1944 | def as_sql(self, compiler, connection, template=None, **extra_context): |
| 1945 | if isinstance(self.expression, ColPairs): |
| 1946 | sql_parts = [] |
| 1947 | params = [] |
| 1948 | for col in self.expression.get_cols(): |
| 1949 | copy = self.copy() |
| 1950 | copy.set_source_expressions([col]) |
| 1951 | sql, col_params = compiler.compile(copy) |
| 1952 | sql_parts.append(sql) |
| 1953 | params.extend(col_params) |
| 1954 | return ", ".join(sql_parts), params |
| 1955 | template = template or self.template |
| 1956 | if connection.features.supports_order_by_nulls_modifier: |
| 1957 | if self.nulls_last: |
| 1958 | template = "%s NULLS LAST" % template |
| 1959 | elif self.nulls_first: |
| 1960 | template = "%s NULLS FIRST" % template |
| 1961 | else: |
| 1962 | if self.nulls_last and not ( |
| 1963 | self.descending and connection.features.order_by_nulls_first |
| 1964 | ): |
| 1965 | template = "%%(expression)s IS NULL, %s" % template |
| 1966 | elif self.nulls_first and not ( |
| 1967 | not self.descending and connection.features.order_by_nulls_first |
| 1968 | ): |
| 1969 | template = "%%(expression)s IS NOT NULL, %s" % template |
| 1970 | connection.ops.check_expression_support(self) |
| 1971 | expression_sql, params = compiler.compile(self.expression) |
| 1972 | placeholders = { |
no outgoing calls