import graphene from django.db.models import Q from graphene import relay, ObjectType from graphene_django import DjangoObjectType from graphene_django.filter import DjangoFilterConnectionField from books.models.snapshot import Snapshot from ..interfaces import ModuleInterface, ChapterInterface from ..interfaces.contentblock import ContentBlockInterface from ...models import Module, Chapter, ChapterSnapshot, ContentBlock class SnapshotContentBlock: def __init__(self, content_block, snapshot): self.id = content_block.id self.pk = content_block.pk self.title = content_block.title self.contents = content_block.contents self.type = content_block.type self.hidden = snapshot.hidden_content_blocks.filter(id=content_block.id).exists() class SnapshotChapter: def __init__(self, chapter, snapshot, description_hidden=False, title_hidden=False): self.id = chapter.id self.pk = chapter.pk self.title = chapter.title self.description = chapter.description self.title_hidden = title_hidden self.description_hidden = description_hidden self.content_blocks = [] base_qs = ContentBlock.get_by_parent(chapter) without_owner = Q(owner__isnull=True) this_snapshot = Q(contentblocksnapshot__snapshot=snapshot) self.content_blocks = [ SnapshotContentBlock( content_block=content_block, snapshot=snapshot ) for content_block in base_qs.filter(without_owner | this_snapshot) ] # all from module without owner # all with snapshotcontentblock with this snapshot class SnapshotContentBlockNode(ObjectType): class Meta: interfaces = (relay.Node, ContentBlockInterface,) hidden = graphene.Boolean() class SnapshotChapterNode(ObjectType): class Meta: interfaces = (relay.Node, ChapterInterface,) content_blocks = graphene.List(SnapshotContentBlockNode) description_hidden = graphene.Boolean() title_hidden = graphene.Boolean() class SnapshotNode(DjangoObjectType): title = graphene.String() chapters = graphene.List(SnapshotChapterNode) meta_title = graphene.String() hero_image = graphene.String() class Meta: model = Snapshot interfaces = (relay.Node,) @staticmethod def resolve_chapters(parent, info, **kwargs): return [ SnapshotChapter( chapter_snapshot.chapter, snapshot=parent, title_hidden=chapter_snapshot.title_hidden, description_hidden=chapter_snapshot.description_hidden ) for chapter_snapshot in parent.chapters.through.objects.filter(snapshot=parent) ] @staticmethod def resolve_title(parent, info, **kwargs): return parent.__str__() @staticmethod def resolve_meta_title(parent, info, **kwargs): return parent.module.meta_title @staticmethod def resolve_hero_image(parent, info, **kwargs): if parent.module.hero_image: return parent.module.hero_image.file.url return ''