schema.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. import graphene
  2. from graphene_django.types import DjangoObjectType
  3. from graphql_jwt.decorators import login_required
  4. from .models import Good,Image
  5. import json
  6. from functools import reduce
  7. from .serializers import GoodSerializer
  8. from django.forms.models import model_to_dict
  9. from django.db.models import Count
  10. from django.conf import settings
  11. import operator
  12. from django.db.models import Q
  13. class ImageType(graphene.ObjectType):
  14. _id = graphene.String(name='_id')
  15. url = graphene.String()
  16. def resolve__id(self,info):
  17. return self._id
  18. def resolve_url(self,info):
  19. return settings.MEDIA_URL + str(self.url)
  20. class ImageInput(graphene.InputObjectType):
  21. _id = graphene.String(name='_id')
  22. url = graphene.String(name='url')
  23. class GoodType(graphene.ObjectType):
  24. _id = graphene.String(name='_id')
  25. images = graphene.List(ImageType)
  26. name = graphene.String()
  27. description = graphene.String()
  28. price = graphene.Int()
  29. amount = graphene.Int()
  30. categories = graphene.List('categories.schema.CategoryType')
  31. createdAt = graphene.String()
  32. def resolve__id(self,info):
  33. return self._id
  34. def resolve_images(self,info):
  35. return self.images.all().order_by("goodimage__order")
  36. def resolve_categories(self,info):
  37. return self.categories.all()
  38. def resolve_name(self,info):
  39. return self.name
  40. def resolve_description(self,info):
  41. return self.description
  42. def resolve_price(self,info):
  43. return self.price
  44. def resolve_amount(self,info):
  45. return self.amount
  46. def resolve_createdAt(self,info):
  47. return self.createdAt.strftime('%s')
  48. class GoodInput(graphene.InputObjectType):
  49. _id = graphene.String(name='_id')
  50. images = graphene.List(ImageInput)
  51. name = graphene.String()
  52. description = graphene.String()
  53. price = graphene.Int()
  54. amount = graphene.Int()
  55. categories = graphene.List('categories.schema.CategoryInput')
  56. class Query(graphene.ObjectType):
  57. GoodFind = graphene.List(GoodType,query = graphene.String())
  58. GoodFindOne = graphene.Field(GoodType,query = graphene.String())
  59. ImageFind = graphene.List(ImageType,query = graphene.String())
  60. ImageFindOne = graphene.Field(ImageType,query = graphene.String())
  61. def resolve_GoodFind(self,info,query = "[{}]"):
  62. additional_params = {}
  63. query_list = json.loads(query)
  64. filter_params = query_list[0]
  65. if len(query_list) > 1:
  66. additional_params = query_list[1]
  67. skip = int(additional_params.get("skip",0))
  68. limit = int(additional_params.get("limit",20))
  69. order_by = additional_params.get("orderBy","_id")
  70. query_set = Good.objects.all()
  71. if len(filter_params):
  72. query_set = query_set.filter(reduce(operator.or_,(Q(**d) for d in [dict([i]) for i in filter_params.items()])))
  73. if order_by == 'popular':
  74. query_set = query_set.annotate(order_count=Count('orderGoods')).order_by("-order_count")[skip:skip+limit]
  75. else:
  76. query_set = query_set.order_by(order_by)[skip:skip+limit]
  77. return query_set
  78. def resolve_GoodFindOne(self,info,query = "[{}]"):
  79. additional_params = {}
  80. query_list = json.loads(query)
  81. filter_params = query_list[0]
  82. if len(query_list) > 1:
  83. additional_params = query_list[1]
  84. skip = additional_params.get("skip",0)
  85. limit = additional_params.get("limit",20)
  86. order_by = additional_params.get("orderBy","_id")
  87. query_set = Good.objects.all()
  88. if len(filter_params):
  89. query_set = query_set.filter(reduce(operator.or_,(Q(**d) for d in [dict([i]) for i in filter_params.items()])))
  90. return query_set.first()
  91. def resolve_ImageFind(self,info,query = "[{}]"):
  92. additional_params = {}
  93. query_list = json.loads(query)
  94. filter_params = query_list[0]
  95. if len(query_list) > 1:
  96. additional_params = query_list[1]
  97. skip = additional_params.get("skip",0)
  98. limit = additional_params.get("limit",20)
  99. order_by = additional_params.get("orderBy","_id")
  100. query_set = Image.objects.all()
  101. if len(filter_params):
  102. query_set = query_set.filter(reduce(operator.and_,(Q(**d) for d in [dict([i]) for i in filter_params.items()])))
  103. return query_set
  104. def resolve_ImageFindOne(self,info,query = "[{}]"):
  105. additional_params = {}
  106. query_list = json.loads(query)
  107. filter_params = query_list[0]
  108. if len(query_list) > 1:
  109. additional_params = query_list[1]
  110. skip = additional_params.get("skip",0)
  111. limit = additional_params.get("limit",20)
  112. order_by = additional_params.get("orderBy","_id")
  113. query_set = Image.objects.all()
  114. if len(filter_params):
  115. try:
  116. query_set = query_set.filter(reduce(operator.and_,(Q(**d) for d in [dict([i]) for i in filter_params.items()])))
  117. except:
  118. raise Exception("Не вірні дані")
  119. return query_set.first()
  120. class GoodUpsert(graphene.Mutation):
  121. class Arguments:
  122. good = GoodInput(required=True)
  123. Output =GoodType
  124. @staticmethod
  125. def mutate(root,info,good):
  126. new_good={}
  127. image_list = None
  128. category_list = None
  129. user = info.context.user
  130. if not user.is_superuser:
  131. raise Exception("Authentication credentials were not provided")
  132. if "images" in good:
  133. image_list = [f["_id"] for f in good["images"]]
  134. # image_list = []
  135. # for idx, image in enumerate(good["images"]):
  136. # image["order"] = idx+1
  137. # image_list.append(image)
  138. good.pop("images",None)
  139. if "categories" in good:
  140. category_list = [f['_id'] for f in good["categories"]]
  141. good.pop("categories",None)
  142. try:
  143. _id = good._id
  144. new_good = Good.objects.get(_id = _id)
  145. good.pop("_id",None)
  146. new_good.__dict__.update(**good)
  147. except Exception as e:
  148. new_good = Good(**good)
  149. new_good.save()
  150. if image_list != None:
  151. new_good.images.set(image_list)
  152. for idx,image in enumerate(image_list):
  153. instance = new_good.GoodImages.get(image = image)
  154. instance.order = idx+1
  155. instance.save()
  156. if category_list != None:
  157. new_good.categories.set(category_list)
  158. new_good.save()
  159. good_data = model_to_dict(new_good)
  160. good_data["_id"] = new_good._id
  161. return GoodType(**good_data)
  162. class GoodDelete(graphene.Mutation):
  163. class Arguments:
  164. good = GoodInput(required=True)
  165. Output =GoodType
  166. @staticmethod
  167. def mutate(root,info,good):
  168. user = info.context.user
  169. if not user.is_superuser:
  170. raise Exception("Authentication credentials were not provided")
  171. try:
  172. _id = good._id
  173. good_to_delete = Good.objects.get(_id=_id)
  174. good_data = model_to_dict(good_to_delete)
  175. good_data["_id"] = good_to_delete ._id
  176. good_to_delete.delete()
  177. except:
  178. raise Exception("Не вірні дані")
  179. return GoodType(**good_data)
  180. class Mutations(graphene.ObjectType):
  181. GoodUpsert = GoodUpsert.Field()
  182. GoodDelete = GoodDelete.Field()