-
Notifications
You must be signed in to change notification settings - Fork 10
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Django models
__str__
codemod (#302)
* initial django dunder str codmeod * attempt to add leading line * make dedent=False * test django dunder str codemod correctly formats model * django dunder str codemod can detect if parent class has a dunder str * document django str dunder codemod * Apply suggestions from code review Co-authored-by: Dan D'Avella <[email protected]> * change from list to gen --------- Co-authored-by: Dan D'Avella <[email protected]>
- Loading branch information
1 parent
7e49478
commit 7075794
Showing
12 changed files
with
299 additions
and
10 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
from core_codemods.django_model_without_dunder_str import ( | ||
DjangoModelWithoutDunderStr, | ||
DjangoModelWithoutDunderStrTransformer, | ||
) | ||
from codemodder.codemods.test import ( | ||
BaseIntegrationTest, | ||
original_and_expected_from_code_path, | ||
) | ||
|
||
|
||
class TestDjangoModelWithoutDunderStr(BaseIntegrationTest): | ||
codemod = DjangoModelWithoutDunderStr | ||
code_path = "tests/samples/django-project/mysite/mysite/models.py" | ||
original_code, expected_new_code = original_and_expected_from_code_path( | ||
code_path, | ||
[ | ||
(15, """\n"""), | ||
(16, """ def __str__(self):\n"""), | ||
(17, """ model_name = self.__class__.__name__\n"""), | ||
( | ||
18, | ||
""" fields_str = ", ".join((f"{field.name}={getattr(self, field.name)}" for field in self._meta.fields))\n""", | ||
), | ||
(19, """ return f"{model_name}({fields_str})"\n"""), | ||
], | ||
) | ||
|
||
# fmt: off | ||
expected_diff =( | ||
"""--- \n""" | ||
"""+++ \n""" | ||
"""@@ -11,3 +11,8 @@\n""" | ||
""" content = models.CharField(max_length=200)\n""" | ||
""" class Meta:\n""" | ||
""" app_label = 'myapp'\n""" | ||
"""+\n""" | ||
"""+ def __str__(self):\n""" | ||
"""+ model_name = self.__class__.__name__\n""" | ||
"""+ fields_str = ", ".join((f"{field.name}={getattr(self, field.name)}" for field in self._meta.fields))\n""" | ||
"""+ return f"{model_name}({fields_str})"\n""" | ||
) | ||
# fmt: on | ||
|
||
expected_line_change = "9" | ||
change_description = DjangoModelWithoutDunderStrTransformer.change_description | ||
num_changed_files = 1 | ||
|
||
def check_code_after(self): | ||
"""Executes models.py and instantiates the model to ensure expected str representation""" | ||
module = super().check_code_after() | ||
inst = module.Message(pk=1, author="name", content="content") | ||
assert str(inst) == "Message(id=1, author=name, content=content)" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,89 @@ | ||
from typing import Union | ||
import libcst as cst | ||
from codemodder.codemods.libcst_transformer import ( | ||
LibcstResultTransformer, | ||
LibcstTransformerPipeline, | ||
) | ||
from codemodder.codemods.utils_mixin import NameResolutionMixin | ||
from core_codemods.api import ( | ||
Metadata, | ||
Reference, | ||
ReviewGuidance, | ||
) | ||
from core_codemods.api.core_codemod import CoreCodemod | ||
|
||
|
||
class DjangoModelWithoutDunderStrTransformer( | ||
LibcstResultTransformer, NameResolutionMixin | ||
): | ||
change_description = "Add `__str__` definition to `django` Model class." | ||
|
||
def leave_ClassDef( | ||
self, original_node: cst.ClassDef, updated_node: cst.ClassDef | ||
) -> Union[ | ||
cst.BaseStatement, cst.FlattenSentinel[cst.BaseStatement], cst.RemovalSentinel | ||
]: | ||
|
||
# TODO: add filter by include or exclude that works for nodes | ||
# that that have different start/end numbers. | ||
if not any( | ||
self.find_base_name(base.value) == "django.db.models.Model" | ||
for base in original_node.bases | ||
): | ||
return updated_node | ||
|
||
if self.implements_dunder_str(original_node): | ||
return updated_node | ||
|
||
self.report_change(original_node) | ||
|
||
new_body = updated_node.body.with_changes( | ||
body=[*updated_node.body.body, dunder_str_method()] | ||
) | ||
return updated_node.with_changes(body=new_body) | ||
|
||
def implements_dunder_str(self, original_node: cst.ClassDef) -> bool: | ||
"""Check if a ClassDef or its bases implement `__str__`""" | ||
if self.class_has_method(original_node, "__str__"): | ||
return True | ||
|
||
for base in original_node.bases: | ||
if maybe_assignment := self.find_single_assignment(base.value): | ||
classdef = maybe_assignment.node | ||
if self.class_has_method(classdef, "__str__"): | ||
return True | ||
return False | ||
|
||
|
||
def dunder_str_method() -> cst.FunctionDef: | ||
self_body = cst.IndentedBlock( | ||
body=[ | ||
cst.parse_statement("model_name = self.__class__.__name__"), | ||
cst.parse_statement( | ||
'fields_str = ", ".join((f"{field.name}={getattr(self, field.name)}" for field in self._meta.fields))' | ||
), | ||
cst.parse_statement('return f"{model_name}({fields_str})"'), | ||
] | ||
) | ||
return cst.FunctionDef( | ||
leading_lines=[cst.EmptyLine(indent=False)], | ||
name=cst.Name("__str__"), | ||
params=cst.Parameters(params=[cst.Param(name=cst.Name("self"))]), | ||
body=self_body, | ||
) | ||
|
||
|
||
DjangoModelWithoutDunderStr = CoreCodemod( | ||
metadata=Metadata( | ||
name="django-model-without-dunder-str", | ||
summary="Ensure Django Model Classes Implement a `__str__` Method", | ||
review_guidance=ReviewGuidance.MERGE_AFTER_REVIEW, | ||
references=[ | ||
Reference( | ||
url="https://docs.djangoproject.com/en/5.0/ref/models/instances/#django.db.models.Model.__str__" | ||
), | ||
], | ||
), | ||
transformer=LibcstTransformerPipeline(DjangoModelWithoutDunderStrTransformer), | ||
detector=None, | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
30 changes: 30 additions & 0 deletions
30
src/core_codemods/docs/pixee_python_django-model-without-dunder-str.md
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
If you've ever actively developed or debugged a Django application, you may have noticed that the string representations of Django models and their instances can sometimes be hard to read or to distinguish from one another. Loading models in the interactive Django console or viewing them in the admin interface can be puzzling. This is because the default string representation of Django models is fairly generic. | ||
|
||
This codemod is intended to make the string representation of your model objects more human-readable. It will automatically detect all of your model's fields and display them as a descriptive string. | ||
|
||
For example, the default string representation of the `Question` model from Django's popular Poll App tutorial looks like this: | ||
```diff | ||
from django.db import models | ||
|
||
class Question(models.Model): | ||
question_text = models.CharField(max_length=200) | ||
pub_date = models.DateTimeField("date published") | ||
+ | ||
+ def __str__(self): | ||
+ model_name = self.__class__.__name__ | ||
+ fields_str = ", ".join((f"{field.name}={getattr(self, field.name)}" for field in self._meta.fields)) | ||
+ return f"{model_name}({fields_str})" | ||
``` | ||
|
||
Without this change, the string representation of `Question` objects look like this in the interactive Django shell: | ||
``` | ||
>>> Question.objects.all() | ||
<QuerySet [<Question: Question object (1)>]> | ||
``` | ||
With this codemod's addition of `__str__`, it now looks like: | ||
``` | ||
>>> Question.objects.all() | ||
<QuerySet [<Question: Question(id=1, question_text=What's new?, pub_date=2024-02-21 14:28:45.631782+00:00)>]> | ||
``` | ||
|
||
You'll notice this change works great for models with only a handful of fields. We encourage you to use this codemod's change as a starting point for further customization. |
2 changes: 1 addition & 1 deletion
2
src/core_codemods/docs/pixee_python_django-session-cookie-secure-off.md
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,75 @@ | ||
from core_codemods.django_model_without_dunder_str import DjangoModelWithoutDunderStr | ||
from codemodder.codemods.test import BaseCodemodTest | ||
|
||
|
||
class TestDjangoModelWithoutDunderStr(BaseCodemodTest): | ||
codemod = DjangoModelWithoutDunderStr | ||
|
||
def test_name(self): | ||
assert self.codemod.name == "django-model-without-dunder-str" | ||
|
||
def test_no_change(self, tmpdir): | ||
input_code = """ | ||
from django.db import models | ||
class User(models.Model): | ||
name = models.CharField(max_length=100) | ||
phone = models.IntegerField(blank=True) | ||
def __str__(self): | ||
return "doesntmatter" | ||
""" | ||
self.run_and_assert(tmpdir, input_code, input_code) | ||
|
||
def test_no_dunder_str(self, tmpdir): | ||
input_code = """ | ||
from django.db import models | ||
class User(models.Model): | ||
name = models.CharField(max_length=100) | ||
phone = models.IntegerField(blank=True) | ||
@property | ||
def decorated_name(self): | ||
return f"***{self.name}***" | ||
def something(): | ||
pass | ||
""" | ||
expected = """ | ||
from django.db import models | ||
class User(models.Model): | ||
name = models.CharField(max_length=100) | ||
phone = models.IntegerField(blank=True) | ||
@property | ||
def decorated_name(self): | ||
return f"***{self.name}***" | ||
def __str__(self): | ||
model_name = self.__class__.__name__ | ||
fields_str = ", ".join((f"{field.name}={getattr(self, field.name)}" for field in self._meta.fields)) | ||
return f"{model_name}({fields_str})" | ||
def something(): | ||
pass | ||
""" | ||
self.run_and_assert(tmpdir, input_code, expected) | ||
|
||
def test_model_inherits_dunder_str(self, tmpdir): | ||
input_code = """ | ||
from django.db import models | ||
class Custom: | ||
def __str__(self): | ||
pass | ||
class User(Custom, models.Model): | ||
name = models.CharField(max_length=100) | ||
phone = models.IntegerField(blank=True) | ||
def something(): | ||
pass | ||
""" | ||
self.run_and_assert(tmpdir, input_code, input_code) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
import django | ||
from django.conf import settings | ||
from django.db import models | ||
# required to run this module standalone for testing | ||
settings.configure() | ||
django.setup() | ||
|
||
|
||
class Message(models.Model): | ||
author = models.CharField(max_length=100) | ||
content = models.CharField(max_length=200) | ||
class Meta: | ||
app_label = 'myapp' |