schema.py 7.3 KB

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