django-stubs icon indicating copy to clipboard operation
django-stubs copied to clipboard

Formset get_queryset() returns QuerySet

Open MrkGrgsn opened this issue 1 year ago • 5 comments

I have made things!

Set the return type of BaseModelFormset.get_queryset() to QuerySet[_M].

In previous version, it has a return type of _IndexableCollection but QuerySet is no longer a type of Collection (https://github.com/typeddjango/django-stubs/discussions/2095) and in Django main branch, 5.0 and 4.2 this function returns a plain old QuerySet.

MrkGrgsn avatar May 21 '24 01:05 MrkGrgsn

Thanks @sobolevn. You're right, QuerySet is insufficient. As far as I can see, uses of get_queryset rely on __iter__ , __getitem__, and __len__ and I couldn't see a type providing that so I created a new abstract collection type. I struggled with finding a generic name that wasn't too long (IndexableSizedIterable?) so went for _QuerySetLike. Let me know what you'd prefer.

MrkGrgsn avatar May 21 '24 23:05 MrkGrgsn

Technically you can return other data types from get_queryset, see https://github.com/django/django/blob/main/django/forms/models.py

That's surprising. What exactly is this link pointing to? I just found one get_queryset method there which does return a QuerySet.

intgr avatar May 22 '24 09:05 intgr

I think it's totally fine to have the method named get_queryset typed to return a QuerySet.

And if there's any user(s) that override the method to change the return type to e.g. list[MyModel] they can just # type: ignore[...].

But if I'm using the default implementation of self.get_queryset() without having done any overrides I would very much like to be able to expect a QuerySet[...] in order to be able to do e.g. self.get_queryset().filter(...) without any errors.

flaeppe avatar May 22 '24 10:05 flaeppe

This is also fine 👍

sobolevn avatar May 22 '24 14:05 sobolevn

If I've followed the thumbsup's correctly, the preferred solution is QuerySet. Let me know if I'm wrong otherwise I'll revert the 2nd commit tomorrow. 👍

MrkGrgsn avatar May 22 '24 23:05 MrkGrgsn

Yes, I think QuerySet[_M] is more appropriate here.

intgr avatar May 23 '24 07:05 intgr

If I've followed the thumbsup's correctly, the preferred solution is QuerySet. Let me know if I'm wrong otherwise I'll revert the 2nd commit tomorrow. 👍

You're right in that the preferred solution is QuerySet[_M] so I think it's enough to drop 8ee0e48cea264c16b8e058fb1d127cbf89e1c037

flaeppe avatar May 24 '24 15:05 flaeppe

Sorry for the delay, I've reverted the 2nd commit.

MrkGrgsn avatar May 26 '24 23:05 MrkGrgsn

Thank you

flaeppe avatar May 27 '24 04:05 flaeppe