query Product objects all subquery Vips objects filter game OuterRef g

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
query = Product.objects.all()
subquery = Vips.objects.filter(game=OuterRef('game'), user=user)
query = query.annotate(
vips=Subquery(subquery.values('user')[:1]),
visible=Case(
When(visibility=Product.VIPS_VISIBLE, then=Q(vips__isnull=False)),
When(visibility=Product.VIPS_INVISIBLE, then=Q(vips__isnull=True)),
default=Value(True),
output_field=BooleanField()
)
).filter(visible=True).distinct()