schema.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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. or_filter_params = filter_params.pop("or",{})
  73. and_filter_params= filter_params.pop("and",{})
  74. and_filter_params |= filter_params
  75. if len(or_filter_params):
  76. query_set = query_set.filter(reduce(operator.or_,(Q(**d) for d in [dict([i]) for i in or_filter_params.items()])))
  77. if len(and_filter_params):
  78. query_set = query_set.filter(reduce(operator.and_,(Q(**d) for d in [dict([i]) for i in and_filter_params.items()])))
  79. if order_by == 'popular':
  80. query_set = query_set.annotate(order_count=Count('orderGoods')).order_by("-order_count")[skip:skip+limit]
  81. else:
  82. query_set = query_set.order_by(order_by)[skip:skip+limit]
  83. return query_set
  84. def resolve_GoodFindOne(self,info,query = "[{}]"):
  85. additional_params = {}
  86. query_list = json.loads(query)
  87. filter_params = query_list[0]
  88. if len(query_list) > 1:
  89. additional_params = query_list[1]
  90. skip = additional_params.get("skip",0)
  91. limit = additional_params.get("limit",20)
  92. order_by = additional_params.get("orderBy","_id")
  93. query_set = Good.objects.all()
  94. if len(filter_params):
  95. or_filter_params = filter_params.pop("or",{})
  96. and_filter_params= filter_params.pop("and",{})
  97. and_filter_params |= filter_params
  98. if len(or_filter_params):
  99. query_set = query_set.filter(reduce(operator.or_,(Q(**d) for d in [dict([i]) for i in or_filter_params.items()])))
  100. if len(and_filter_params):
  101. query_set = query_set.filter(reduce(operator.and_,(Q(**d) for d in [dict([i]) for i in and_filter_params.items()])))
  102. return query_set.first()
  103. def resolve_ImageFind(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. or_filter_params = filter_params.pop("or",{})
  115. and_filter_params= filter_params.pop("and",{})
  116. and_filter_params |= filter_params
  117. if len(or_filter_params):
  118. query_set = query_set.filter(reduce(operator.or_,(Q(**d) for d in [dict([i]) for i in or_filter_params.items()])))
  119. if len(and_filter_params):
  120. query_set = query_set.filter(reduce(operator.and_,(Q(**d) for d in [dict([i]) for i in and_filter_params.items()])))
  121. return query_set
  122. def resolve_ImageFindOne(self,info,query = "[{}]"):
  123. additional_params = {}
  124. query_list = json.loads(query)
  125. filter_params = query_list[0]
  126. if len(query_list) > 1:
  127. additional_params = query_list[1]
  128. skip = additional_params.get("skip",0)
  129. limit = additional_params.get("limit",20)
  130. order_by = additional_params.get("orderBy","_id")
  131. query_set = Image.objects.all()
  132. if len(filter_params):
  133. try:
  134. or_filter_params = filter_params.pop("or",{})
  135. and_filter_params= filter_params.pop("and",{})
  136. and_filter_params |= filter_params
  137. if len(or_filter_params):
  138. query_set = query_set.filter(reduce(operator.or_,(Q(**d) for d in [dict([i]) for i in or_filter_params.items()])))
  139. if len(and_filter_params):
  140. query_set = query_set.filter(reduce(operator.and_,(Q(**d) for d in [dict([i]) for i in and_filter_params.items()])))
  141. except:
  142. raise Exception("Не вірні дані")
  143. return query_set.first()
  144. class GoodUpsert(graphene.Mutation):
  145. class Arguments:
  146. good = GoodInput(required=True)
  147. Output =GoodType
  148. @staticmethod
  149. def mutate(root,info,good):
  150. new_good={}
  151. image_list = None
  152. category_list = None
  153. user = info.context.user
  154. if not user.is_superuser:
  155. raise Exception("Authentication credentials were not provided")
  156. if "images" in good:
  157. image_list = [f["_id"] for f in good["images"]]
  158. # image_list = []
  159. # for idx, image in enumerate(good["images"]):
  160. # image["order"] = idx+1
  161. # image_list.append(image)
  162. good.pop("images",None)
  163. if "categories" in good:
  164. category_list = [f['_id'] for f in good["categories"]]
  165. good.pop("categories",None)
  166. try:
  167. _id = good._id
  168. new_good = Good.objects.get(_id = _id)
  169. good.pop("_id",None)
  170. new_good.__dict__.update(**good)
  171. except Exception as e:
  172. new_good = Good(**good)
  173. new_good.save()
  174. if image_list != None:
  175. new_good.images.set(image_list)
  176. for idx,image in enumerate(image_list):
  177. instance = new_good.GoodImages.get(image = image)
  178. instance.order = idx+1
  179. instance.save()
  180. if category_list != None:
  181. new_good.categories.set(category_list)
  182. new_good.save()
  183. good_data = model_to_dict(new_good)
  184. good_data["_id"] = new_good._id
  185. return GoodType(**good_data)
  186. class GoodDelete(graphene.Mutation):
  187. class Arguments:
  188. good = GoodInput(required=True)
  189. Output =GoodType
  190. @staticmethod
  191. def mutate(root,info,good):
  192. user = info.context.user
  193. if not user.is_superuser:
  194. raise Exception("Authentication credentials were not provided")
  195. try:
  196. _id = good._id
  197. good_to_delete = Good.objects.get(_id=_id)
  198. good_data = model_to_dict(good_to_delete)
  199. good_data["_id"] = good_to_delete ._id
  200. good_to_delete.delete()
  201. except:
  202. raise Exception("Не вірні дані")
  203. return GoodType(**good_data)
  204. class Mutations(graphene.ObjectType):
  205. GoodUpsert = GoodUpsert.Field()
  206. GoodDelete = GoodDelete.Field()