Product objects all annotate vips RawSQL SELECT user_id FROM products_

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
Product.objects.all().annotate(
vips=RawSQL(
'SELECT v.user_id FROM products_product as p LEFT JOIN products_vips as v ON v.game_id=p.game_id AND v.user_id=%s LIMIT 1',
params=(user3,)
),
visible=Case(
When(visibility='v', then=Q(game__vips__isnull=False)),
When(visibility='i', then=Q(game__vips__isnull=True)),
default=Value(True),
output_field=BooleanField())).filter(visible=True).distinct().values_list('id', flat=True)
SELECT DISTINCT `products_product`.`id`, `products_product`.`priority` FROM `products_product`
LEFT OUTER JOIN `products_game` ON (`products_product`.`game_id` = `products_game`.`id`)
LEFT OUTER JOIN `products_vips` ON (`products_game`.`id` = `products_vips`.`game_id`)
WHERE CASE
WHEN (`products_product`.`visibility` = 'v') THEN (`products_vips`.`id` IS NOT NULL)
WHEN (`products_product`.`visibility` = 'i') THEN (`products_vips`.`id` IS NULL)
ELSE 1 END = 1 ORDER BY `products_product`.`priority` DESC LIMIT 21; args=('v', 'i', True, True)