6 | | >>> a = Tenant.objects.filter(id__in=[1, 3]).values('id').annotate(schema=F('schema_name'), created=F('created_at')) |
7 | | >>> b = Tenant.objects.filter(id=2).values('id').annotate(schema=F('schema_name'), created=F('created_at')) |
8 | | >>> c = (a|b).distinct() |
9 | | >>> d = c.filter(id=OuterRef('id')).values('schema') |
10 | | >>> e = Tenant.objects.values('schema_name').annotate(created_at=Subquery(d.values('created'))) |
| 6 | class Foo(models.Model): |
| 7 | name = models.CharField(max_length=255) |
| 8 | |
| 9 | class Mapping(models.Model): |
| 10 | field = models.CharField(max_length=255) |
| 11 | foo = models.ForeignKey(Foo, null=True, blank=True, on_delete=models.PROTECT) |
| 12 | |
| 13 | class Tenant(TenantMixin): |
| 14 | created_at = models.DateField(auto_now_add=True) |
| 15 | mapping = models.ForeignKey(Mapping, null=True, blank=True, on_delete=models.PROTECT) |
| 16 | }}} |
| 17 | |
| 18 | Code: |
| 19 | |
| 20 | {{{ |
| 21 | a = Mapping.objects.filter(id=1).values('id').annotate(foo=F('foo__name'),foo_id=F('foo_id')) |
| 22 | b = Mapping.objects.filter(id=2).values('id').annotate(foo=F('foo__name'),foo_id=F('foo_id')) |
| 23 | c = (a|b).distinct() |
| 24 | d = c.filter(id=OuterRef('mapping_id')).values('foo') |
| 25 | e = Tenant.objects.values('id').annotate(foo_id=Subquery(d.values('foo_id'))) |