I have two models - Project
and Contract
.
They have one-to-many relationship.
class Contract(models.Model):
project = models.ForeignKey(Project)
我得到了一个Project
个实例的qs与相关的Contract
个实例.
projects = Project.objects.filter(active=True).prefetch_related(
Prefetch('contract_set', queryset=Contract.objects.filter(**filters), to_attr='contracts')
)
但现在我需要通过将Contract
GUID放置到filters
来获得Project
个实例.
filters: Dict = {
'guid': some_guid,
}
但我收到了所有Project
个实例,其中只有一个实例没有空contracts
attr,其他Project
个实例有空contracts
attr.
I found such issues:
How to exclude rows with empty prefetch_related field
Filter prefetch_related empty in django
but they do not help me.
I tried such options:
a) using OuterRef
and Exist
:
projects = Project.objects.filter(**filters_projects).annotate(
has_contracts=Exists(
Contract.objects.filter(project_id=OuterRef('pk'), **filters_contracts)
)
)
projects = projects.filter(has_contracts=True)
b)使用annotate
:
projects = (
Project.objects.filter(**filters_projects)
.annotate(num_contracts=Count('contract'))
.exclude(num_contracts=0)
.prefetch_related(
Prefetch('contract_set', queryset=Contract.objects.filter(**filters_contracts), to_attr='contracts')
)
)
他们不为我工作…
如何实现所需的功能?