Apply limit_choices_to to the formfield's queryset if needed.
(formfield)
| 122 | |
| 123 | |
| 124 | def apply_limit_choices_to_to_formfield(formfield): |
| 125 | """Apply limit_choices_to to the formfield's queryset if needed.""" |
| 126 | from django.db.models import Exists, OuterRef, Q |
| 127 | |
| 128 | if hasattr(formfield, "queryset") and hasattr(formfield, "get_limit_choices_to"): |
| 129 | limit_choices_to = formfield.get_limit_choices_to() |
| 130 | if limit_choices_to: |
| 131 | complex_filter = limit_choices_to |
| 132 | if not isinstance(complex_filter, Q): |
| 133 | complex_filter = Q(**limit_choices_to) |
| 134 | complex_filter &= Q(pk=OuterRef("pk")) |
| 135 | # Use Exists() to avoid potential duplicates. |
| 136 | formfield.queryset = formfield.queryset.filter( |
| 137 | Exists(formfield.queryset.model._base_manager.filter(complex_filter)), |
| 138 | ) |
| 139 | |
| 140 | |
| 141 | def fields_for_model( |
no test coverage detected