-
-
Notifications
You must be signed in to change notification settings - Fork 450
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
Add better support for ManyToManyField
's through
model
#1719
Merged
Merged
Changes from 1 commit
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
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
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 |
---|---|---|
|
@@ -10,8 +10,10 @@ | |
from mypy.nodes import ( | ||
GDEF, | ||
MDEF, | ||
AssignmentStmt, | ||
Block, | ||
ClassDef, | ||
Context, | ||
Expression, | ||
MemberExpr, | ||
MypyFile, | ||
|
@@ -33,7 +35,8 @@ | |
SemanticAnalyzerPluginInterface, | ||
) | ||
from mypy.semanal import SemanticAnalyzer | ||
from mypy.types import AnyType, Instance, NoneTyp, TupleType, TypedDictType, TypeOfAny, UnionType | ||
from mypy.semanal_shared import parse_bool | ||
from mypy.types import AnyType, Instance, LiteralType, NoneTyp, TupleType, TypedDictType, TypeOfAny, UnionType | ||
from mypy.types import Type as MypyType | ||
from typing_extensions import TypedDict | ||
|
||
|
@@ -45,12 +48,14 @@ | |
|
||
|
||
class DjangoTypeMetadata(TypedDict, total=False): | ||
is_abstract_model: bool | ||
from_queryset_manager: str | ||
reverse_managers: Dict[str, str] | ||
baseform_bases: Dict[str, int] | ||
manager_bases: Dict[str, int] | ||
model_bases: Dict[str, int] | ||
queryset_bases: Dict[str, int] | ||
m2m_throughs: Dict[str, str] | ||
|
||
|
||
def get_django_metadata(model_info: TypeInfo) -> DjangoTypeMetadata: | ||
|
@@ -385,3 +390,61 @@ def add_new_manager_base(api: SemanticAnalyzerPluginInterface, fullname: str) -> | |
if sym is not None and isinstance(sym.node, TypeInfo): | ||
bases = get_django_metadata_bases(sym.node, "manager_bases") | ||
bases[fullname] = 1 | ||
|
||
|
||
def is_abstract_model(model: TypeInfo) -> bool: | ||
if model.metaclass_type is None or model.metaclass_type.type.fullname != fullnames.MODEL_METACLASS_FULLNAME: | ||
return False | ||
|
||
metadata = get_django_metadata(model) | ||
if metadata.get("is_abstract_model") is not None: | ||
return metadata["is_abstract_model"] | ||
|
||
meta = model.names.get("Meta") | ||
# Check if 'abstract' is declared in this model's 'class Meta' as | ||
# 'abstract = True' won't be inherited from a parent model. | ||
if meta is not None and isinstance(meta.node, TypeInfo) and "abstract" in meta.node.names: | ||
for stmt in meta.node.defn.defs.body: | ||
if ( | ||
# abstract = | ||
isinstance(stmt, AssignmentStmt) | ||
and len(stmt.lvalues) == 1 | ||
and isinstance(stmt.lvalues[0], NameExpr) | ||
and stmt.lvalues[0].name == "abstract" | ||
): | ||
# abstract = True (builtins.bool) | ||
rhs_is_true = parse_bool(stmt.rvalue) is True | ||
# abstract: Literal[True] | ||
is_literal_true = isinstance(stmt.type, LiteralType) and stmt.type.value is True | ||
metadata["is_abstract_model"] = rhs_is_true or is_literal_true | ||
return metadata["is_abstract_model"] | ||
|
||
metadata["is_abstract_model"] = False | ||
return False | ||
|
||
|
||
def resolve_lazy_reference( | ||
reference: str, *, api: Union[TypeChecker, SemanticAnalyzer], django_context: "DjangoContext", ctx: Context | ||
) -> Optional[TypeInfo]: | ||
""" | ||
Attempts to resolve a lazy reference(e.g. "<app_label>.<object_name>") to a | ||
'TypeInfo' instance. | ||
""" | ||
if "." not in reference: | ||
# <object_name> -- needs prefix of <app_label>. We can't implicitly solve | ||
# what app label this should be, yet. | ||
return None | ||
Comment on lines
+433
to
+436
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We have a case of this at least (the referenced model is defined right below in the file), which now causes "Needs type annotation" errors |
||
|
||
# Reference conforms to the structure of a lazy reference: '<app_label>.<object_name>' | ||
fullname = django_context.model_class_fullnames_by_label.get(reference) | ||
if fullname is not None: | ||
model_info = lookup_fully_qualified_typeinfo(api, fullname) | ||
if model_info is not None: | ||
return model_info | ||
elif isinstance(api, SemanticAnalyzer) and not api.final_iteration: | ||
# Getting this far, where Django matched the reference but we still can't | ||
# find it, we want to defer | ||
api.defer() | ||
else: | ||
api.fail("Could not match lazy reference with any model", ctx) | ||
return 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
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.
Can we make it generic on all the things and simplify our plugin a bit?
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.
Which parts are you referring to?
The plugin only acts on what is
_T
and_M
here, essentially theto=
andthrough=
argument onManyToManyField
.It does however have to sort some stuff out when there was no explicit
through=
argument passed, as Django automatically generates a through model behind the scenes in that case.Additionally it supports resolving lazy references e.g.
"myapp.MyModel"
and replaces either_T
or_M
with any found model type.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.
What I meant to say here was: which other parts should we make generic to simplify the plugin?
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.
_GT, _ST
? Will it help?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.
No, this changes so that those arguments aren't used at all any more, for
ManyToManyField
. It's just the parent class that wants them.The generics of the descriptor class does almost all the work now instead (except when
through
is implicit, then the plugin does that part)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.
It's a bit hard to follow, but instead of using
_GT
and_ST
and let our plugin do all the work, I've updated the descriptor classManyToManyDescriptor
to become generic over a model, and that will be thethrough=
model for aManyToManyField()
.And if you now look a bit further, you find:
ManyToManyDescriptor.through -> type[_M]
which means that thethrough=
argument align with theMyModel.m2m_field.through
without any plugin work (again, except for special cases of lazy referencing or not passing thethrough=
argument, which is all the new plugin code you see in this PR)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.
Corresponding part is the
to=
argument, plugin code will only be running for lazy referencing. Previously this was completely managed by the plugin, now it's instead mypy doing the work.