-
Notifications
You must be signed in to change notification settings - Fork 10
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Django models __str__
codemod
#302
Merged
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
e478c9e
initial django dunder str codmeod
clavedeluna 233ada2
attempt to add leading line
clavedeluna 25d79a9
make dedent=False
clavedeluna 435dc45
test django dunder str codemod correctly formats model
clavedeluna e73b592
django dunder str codemod can detect if parent class has a dunder str
clavedeluna 93d81b9
document django str dunder codemod
clavedeluna ef37526
Apply suggestions from code review
clavedeluna f82f43d
change from list to gen
clavedeluna File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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' |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Not a huge deal but I feel like we're sometimes inconsistent as to whether a codemod is phrased in terms of a problem or a fix. I think we should prefer names in terms of fixes
add-django-model-dunder-str
but maybe we can just take it as a suggestion going forward.