diff options
| author | Daniyal <abbasi.daniyal98@gmail.com> | 2021-03-24 11:15:08 +0530 |
|---|---|---|
| committer | Mariusz Felisiak <felisiak.mariusz@gmail.com> | 2021-07-15 11:43:33 +0200 |
| commit | f479df7f8d03ab767bb5e5d655243191087d6432 (patch) | |
| tree | bf6f248ad7938a0d9f77ea616a59fba2d5a8befb /django | |
| parent | 08f077888548a951f01b454d0db08d9407f7f0aa (diff) | |
Refs #32508 -- Raised Type/ValueError instead of using "assert" in django.db.models.
Co-authored-by: Mariusz Felisiak <felisiak.mariusz@gmail.com>
Diffstat (limited to 'django')
| -rw-r--r-- | django/db/models/base.py | 10 | ||||
| -rw-r--r-- | django/db/models/fields/__init__.py | 9 | ||||
| -rw-r--r-- | django/db/models/fields/related.py | 30 | ||||
| -rw-r--r-- | django/db/models/functions/datetime.py | 7 | ||||
| -rw-r--r-- | django/db/models/indexes.py | 9 | ||||
| -rw-r--r-- | django/db/models/query.py | 34 | ||||
| -rw-r--r-- | django/db/models/sql/query.py | 12 |
7 files changed, 62 insertions, 49 deletions
diff --git a/django/db/models/base.py b/django/db/models/base.py index b1202f51c7..f208067aae 100644 --- a/django/db/models/base.py +++ b/django/db/models/base.py @@ -947,12 +947,12 @@ class Model(metaclass=ModelBase): field.delete_cached_value(self) def delete(self, using=None, keep_parents=False): + if self.pk is None: + raise ValueError( + "%s object can't be deleted because its %s attribute is set " + "to None." % (self._meta.object_name, self._meta.pk.attname) + ) using = using or router.db_for_write(self.__class__, instance=self) - assert self.pk is not None, ( - "%s object can't be deleted because its %s attribute is set to None." % - (self._meta.object_name, self._meta.pk.attname) - ) - collector = Collector(using=using) collector.collect([self], keep_parents=keep_parents) return collector.delete() diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py index 84c81f9e21..7198d430ce 100644 --- a/django/db/models/fields/__init__.py +++ b/django/db/models/fields/__init__.py @@ -2484,10 +2484,11 @@ class AutoFieldMixin: return value def contribute_to_class(self, cls, name, **kwargs): - assert not cls._meta.auto_field, ( - "Model %s can't have more than one auto-generated field." - % cls._meta.label - ) + if cls._meta.auto_field: + raise ValueError( + "Model %s can't have more than one auto-generated field." + % cls._meta.label + ) super().contribute_to_class(cls, name, **kwargs) cls._meta.auto_field = self diff --git a/django/db/models/fields/related.py b/django/db/models/fields/related.py index a0e8da10fd..8f2a367d65 100644 --- a/django/db/models/fields/related.py +++ b/django/db/models/fields/related.py @@ -815,13 +815,13 @@ class ForeignKey(ForeignObject): try: to._meta.model_name except AttributeError: - assert isinstance(to, str), ( - "%s(%r) is invalid. First parameter to ForeignKey must be " - "either a model, a model name, or the string %r" % ( - self.__class__.__name__, to, - RECURSIVE_RELATIONSHIP_CONSTANT, + if not isinstance(to, str): + raise TypeError( + '%s(%r) is invalid. First parameter to ForeignKey must be ' + 'either a model, a model name, or the string %r' % ( + self.__class__.__name__, to, RECURSIVE_RELATIONSHIP_CONSTANT, + ) ) - ) else: # For backwards compatibility purposes, we need to *try* and set # the to_field during FK construction. It won't be guaranteed to @@ -1169,18 +1169,20 @@ class ManyToManyField(RelatedField): try: to._meta except AttributeError: - assert isinstance(to, str), ( - "%s(%r) is invalid. First parameter to ManyToManyField must be " - "either a model, a model name, or the string %r" % - (self.__class__.__name__, to, RECURSIVE_RELATIONSHIP_CONSTANT) - ) + if not isinstance(to, str): + raise TypeError( + '%s(%r) is invalid. First parameter to ManyToManyField ' + 'must be either a model, a model name, or the string %r' % ( + self.__class__.__name__, to, RECURSIVE_RELATIONSHIP_CONSTANT, + ) + ) if symmetrical is None: symmetrical = (to == RECURSIVE_RELATIONSHIP_CONSTANT) - if through is not None: - assert db_table is None, ( - "Cannot specify a db_table if an intermediary model is used." + if through is not None and db_table is not None: + raise ValueError( + 'Cannot specify a db_table if an intermediary model is used.' ) kwargs['rel'] = self.rel_class( diff --git a/django/db/models/functions/datetime.py b/django/db/models/functions/datetime.py index 7fc49897b5..20161bef38 100644 --- a/django/db/models/functions/datetime.py +++ b/django/db/models/functions/datetime.py @@ -214,9 +214,10 @@ class TruncBase(TimezoneMixin, Transform): copy = super().resolve_expression(query, allow_joins, reuse, summarize, for_save) field = copy.lhs.output_field # DateTimeField is a subclass of DateField so this works for both. - assert isinstance(field, (DateField, TimeField)), ( - "%r isn't a DateField, TimeField, or DateTimeField." % field.name - ) + if not isinstance(field, (DateField, TimeField)): + raise TypeError( + "%r isn't a DateField, TimeField, or DateTimeField." % field.name + ) # If self.output_field was None, then accessing the field will trigger # the resolver to assign it to self.lhs.output_field. if not isinstance(copy.output_field, (DateField, DateTimeField, TimeField)): diff --git a/django/db/models/indexes.py b/django/db/models/indexes.py index cc91c70479..9c393ca2c0 100644 --- a/django/db/models/indexes.py +++ b/django/db/models/indexes.py @@ -161,10 +161,11 @@ class Index: column_names[0][:7], '%s_%s' % (names_digest(*hash_data, length=6), self.suffix), ) - assert len(self.name) <= self.max_name_length, ( - 'Index too long for multiple database support. Is self.suffix ' - 'longer than 3 characters?' - ) + if len(self.name) > self.max_name_length: + raise ValueError( + 'Index too long for multiple database support. Is self.suffix ' + 'longer than 3 characters?' + ) if self.name[0] == '_' or self.name[0].isdigit(): self.name = 'D%s' % self.name[1:] diff --git a/django/db/models/query.py b/django/db/models/query.py index 7856cf1a9f..71a52fb754 100644 --- a/django/db/models/query.py +++ b/django/db/models/query.py @@ -291,10 +291,14 @@ class QuerySet: 'QuerySet indices must be integers or slices, not %s.' % type(k).__name__ ) - assert ((not isinstance(k, slice) and (k >= 0)) or - (isinstance(k, slice) and (k.start is None or k.start >= 0) and - (k.stop is None or k.stop >= 0))), \ - "Negative indexing is not supported." + if ( + (isinstance(k, int) and k < 0) or + (isinstance(k, slice) and ( + (k.start is not None and k.start < 0) or + (k.stop is not None and k.stop < 0) + )) + ): + raise ValueError('Negative indexing is not supported.') if self._result_cache is not None: return self._result_cache[k] @@ -480,7 +484,8 @@ class QuerySet: # PostgreSQL via the RETURNING ID clause. It should be possible for # Oracle as well, but the semantics for extracting the primary keys is # trickier so it's not done yet. - assert batch_size is None or batch_size > 0 + if batch_size is not None and batch_size <= 0: + raise ValueError('Batch size must be a positive integer.') # Check that the parents share the same concrete model with the our # model to detect the inheritance pattern ConcreteGrandParent -> # MultiTableParent -> ProxyChild. Simply checking self.model._meta.proxy @@ -900,10 +905,10 @@ class QuerySet: Return a list of date objects representing all available dates for the given field_name, scoped to 'kind'. """ - assert kind in ('year', 'month', 'week', 'day'), \ - "'kind' must be one of 'year', 'month', 'week', or 'day'." - assert order in ('ASC', 'DESC'), \ - "'order' must be either 'ASC' or 'DESC'." + if kind not in ('year', 'month', 'week', 'day'): + raise ValueError("'kind' must be one of 'year', 'month', 'week', or 'day'.") + if order not in ('ASC', 'DESC'): + raise ValueError("'order' must be either 'ASC' or 'DESC'.") return self.annotate( datefield=Trunc(field_name, kind, output_field=DateField()), plain_field=F(field_name) @@ -916,10 +921,13 @@ class QuerySet: Return a list of datetime objects representing all available datetimes for the given field_name, scoped to 'kind'. """ - assert kind in ('year', 'month', 'week', 'day', 'hour', 'minute', 'second'), \ - "'kind' must be one of 'year', 'month', 'week', 'day', 'hour', 'minute', or 'second'." - assert order in ('ASC', 'DESC'), \ - "'order' must be either 'ASC' or 'DESC'." + if kind not in ('year', 'month', 'week', 'day', 'hour', 'minute', 'second'): + raise ValueError( + "'kind' must be one of 'year', 'month', 'week', 'day', " + "'hour', 'minute', or 'second'." + ) + if order not in ('ASC', 'DESC'): + raise ValueError("'order' must be either 'ASC' or 'DESC'.") if settings.USE_TZ: if tzinfo is None: tzinfo = timezone.get_current_timezone() diff --git a/django/db/models/sql/query.py b/django/db/models/sql/query.py index 2412e6ad4e..b3d92d786c 100644 --- a/django/db/models/sql/query.py +++ b/django/db/models/sql/query.py @@ -567,14 +567,14 @@ class Query(BaseExpression): The 'connector' parameter describes how to connect filters from the 'rhs' query. """ - assert self.model == rhs.model, \ - "Cannot combine queries on two different base models." + if self.model != rhs.model: + raise TypeError('Cannot combine queries on two different base models.') if self.is_sliced: raise TypeError('Cannot combine queries once a slice has been taken.') - assert self.distinct == rhs.distinct, \ - "Cannot combine a unique query with a non-unique query." - assert self.distinct_fields == rhs.distinct_fields, \ - "Cannot combine queries with different distinct fields." + if self.distinct != rhs.distinct: + raise TypeError('Cannot combine a unique query with a non-unique query.') + if self.distinct_fields != rhs.distinct_fields: + raise TypeError('Cannot combine queries with different distinct fields.') # Work out how to relabel the rhs aliases, if necessary. change_map = {} |
