Coverage for sites/comments_site/comments_database/model_helpers.py: 100%

9 statements  

« prev     ^ index     » next       coverage.py v7.3.2, created at 2024-02-28 09:09 +0000

1from .models import Comment 

2from .models import User 

3 

4 

5def comments_default_queryset(): 

6 comments = Comment.objects.prefetch_related( 

7 "site", "parent", "moderationrights_set", "moderators" 

8 ) 

9 return comments 

10 #### Here is a try to annotate directly in the comment queryset the data of the 

11 #### ModerationRights related to the comment having date_moderated NOT NULL. 

12 #### This is super easy in raw SQL: 

13 #### ``` 

14 #### SELECT comment.*, r.* 

15 #### FROM comment 

16 #### LEFT JOIN moderation_rights r ON r.comment_id = comment.id AND r.date_moderated IS NOT NULL 

17 #### ``` 

18 #### However this is quite troublesome with Django. 

19 #### This first try is successfully annotating the moderation data as a JSON field using a subquery 

20 #### The drawback is that it's way less effecive than the desired raw SQL writed above. 

21 # return comments.annotate(moderation=Subquery( 

22 # ModerationRights.objects.filter(comment=OuterRef("pk"), date_moderated__isnull=False).values(data=JSONObject(moderator_id="moderator_id", date_added="date_added", date_moderation="date_moderation"))[:1] 

23 # )) 

24 #### This one correctly selects everyfield, however they are only accessible if we use values() queryset method (stupid ?). 

25 # return comments.annotate( 

26 # moderation=FilteredRelation('moderationrights', condition=Q(moderationrights__date_moderated__isnull=False)) 

27 # ).select_related('moderation') 

28 

29 

30def get_all_comments(): 

31 return comments_default_queryset().all() 

32 

33 

34def get_comments_for_site(site: User): 

35 return comments_default_queryset().filter(site=site)