[`flake8-django`] Apply `DJ001` to annotated fields (#20907)

This commit is contained in:
Dan Parizher 2025-10-27 04:19:15 -04:00 committed by GitHub
parent fa12fd0184
commit 8a73519b25
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 42 additions and 2 deletions

View File

@ -46,3 +46,9 @@ class CorrectModel(models.Model):
max_length=255, null=True, blank=True, unique=True
)
urlfieldu = models.URLField(max_length=255, null=True, blank=True, unique=True)
class IncorrectModelWithSimpleAnnotations(models.Model):
charfield: models.CharField = models.CharField(max_length=255, null=True)
textfield: models.TextField = models.TextField(max_length=255, null=True)
slugfield: models.SlugField = models.SlugField(max_length=255, null=True)

View File

@ -61,9 +61,14 @@ pub(crate) fn nullable_model_string_field(checker: &Checker, body: &[Stmt]) {
}
for statement in body {
let Stmt::Assign(ast::StmtAssign { value, .. }) = statement else {
continue;
let value = match statement {
Stmt::Assign(ast::StmtAssign { value, .. }) => value,
Stmt::AnnAssign(ast::StmtAnnAssign {
value: Some(value), ..
}) => value,
_ => continue,
};
if let Some(field_name) = is_nullable_field(value, checker.semantic()) {
checker.report_diagnostic(
DjangoNullableModelStringField {

View File

@ -186,3 +186,32 @@ DJ001 Avoid using `null=True` on string-based fields such as `URLField`
30 | urlfield = models.URLField(max_length=255, null=True)
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
DJ001 Avoid using `null=True` on string-based fields such as `CharField`
--> DJ001.py:52:35
|
51 | class IncorrectModelWithSimpleAnnotations(models.Model):
52 | charfield: models.CharField = models.CharField(max_length=255, null=True)
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
53 | textfield: models.TextField = models.TextField(max_length=255, null=True)
54 | slugfield: models.SlugField = models.SlugField(max_length=255, null=True)
|
DJ001 Avoid using `null=True` on string-based fields such as `TextField`
--> DJ001.py:53:35
|
51 | class IncorrectModelWithSimpleAnnotations(models.Model):
52 | charfield: models.CharField = models.CharField(max_length=255, null=True)
53 | textfield: models.TextField = models.TextField(max_length=255, null=True)
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
54 | slugfield: models.SlugField = models.SlugField(max_length=255, null=True)
|
DJ001 Avoid using `null=True` on string-based fields such as `SlugField`
--> DJ001.py:54:35
|
52 | charfield: models.CharField = models.CharField(max_length=255, null=True)
53 | textfield: models.TextField = models.TextField(max_length=255, null=True)
54 | slugfield: models.SlugField = models.SlugField(max_length=255, null=True)
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|