Type hint custom Django model manager - correct way? #6077
Unanswered
dfillingham
asked this question in
Q&A
Replies: 1 comment
-
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.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
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