Type hint custom Django model manager - correct way? #6077
Replies: 3 comments 7 replies
-
I'll try to answer some of your questions. For the objects annotation, you can do this:
Type annotations in a class that reference that class can put quotes around a type. It's a forward reference. For the
For the |
Beta Was this translation helpful? Give feedback.
-
You should provide a type to your custom manager using a forward reference, like this: class SalesOrderManager(models.Manager['SalesOrder']) Then you should explicitly annotate the objects: SalesOrderManager = SalesOrderManager() Otherwise, Pylance infers the type of the manager as |
Beta Was this translation helpful? Give feedback.
-
what about the queryset results? like this: class MyQuerySet(models.QuerySet["MyModel"]):
def my_filter_or_method_on_queryset(self,*args,**kwargs):
return self.filter(...)
class MyManager(models.manager.BaseManager.from_queryset(MyQuerySet)):
def my_filter_or_method_on_manager(self,*args,**kwargs):
return self.filter(...)
class MyModel(models.Model):
...
objects = MyManager() this is a very basic setup and pylance can even check the types when doing filters on top of MyManager and also lints the method UPDATE: |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Hi,
What is the correct way to type hint a custom django model manager so that Intellisense will work when interacting with the manager via
.objects
and also when returning model instances from the built-in django queryset APIs?Python version - 3.10.12
Django version - 5.0
Pylance version - v2024.6.1
A simple model & manager to demonstrate the issue I'm facing:
If I annotate
objects
like so:objects: SalesOrderManager = SalesOrderManager()
then Intellisense works to find the custom functioncreate_sales_order
on the manager, however built-in Django APIs such asget
,first
etc are not typed asSalesOrder
so theis_order_open
function isn't found, nor are the model's fields.This also occurs if I annotate as
objects: SalesOrderManager[Self] = SalesOrderManager()
If I try to annotate
objects
like so:objects: SalesOrderManager[SalesOrder] = SalesOrderManager()
then I get an error thatSalesOrder is not yet defined
If I try to annotate
objects
like so:objects: Manager[SalesOrder] = SalesOrderManager()
then I get the inverse, built-in APIs returning model instances are typed correctly however the custom manager function is not found:Beta Was this translation helpful? Give feedback.
All reactions