models.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. # Copyright © 2023 Ingram Micro Inc. All rights reserved.
  2. from django.contrib.auth.models import AbstractUser
  3. from django.core.cache import cache
  4. from django.db import models
  5. from dj_cqrs.mixins import ReplicaMixin
  6. class User(ReplicaMixin, AbstractUser):
  7. """
  8. Simple replica which sync all fields
  9. """
  10. CQRS_ID = 'user'
  11. class ProductType(models.Model):
  12. name = models.CharField(max_length=50)
  13. class Product(ReplicaMixin, models.Model):
  14. """
  15. Replica with custom serialization and relation control
  16. """
  17. CQRS_ID = 'product'
  18. CQRS_CUSTOM_SERIALIZATION = True
  19. name = models.CharField(max_length=100)
  20. product_type = models.ForeignKey(ProductType, on_delete=models.CASCADE)
  21. @staticmethod
  22. def _handle_product_type(mapped_data):
  23. product_type, _ = ProductType.objects.update_or_create(
  24. id=mapped_data['id'],
  25. defaults=mapped_data,
  26. )
  27. return product_type
  28. @classmethod
  29. def cqrs_create(cls, sync, mapped_data, previous_data=None, meta=None):
  30. product_type = cls._handle_product_type(mapped_data['product_type'])
  31. return Product.objects.create(
  32. id=mapped_data['id'],
  33. product_type_id=product_type.id,
  34. name=mapped_data['name'],
  35. cqrs_revision=mapped_data['cqrs_revision'],
  36. cqrs_updated=mapped_data['cqrs_updated'],
  37. )
  38. def cqrs_update(self, sync, mapped_data, previous_data=None, meta=None):
  39. product_type = self._handle_product_type(mapped_data['product_type'])
  40. self.name = mapped_data['name']
  41. self.product_type_id = product_type.id
  42. self.save()
  43. return self
  44. class Purchase(ReplicaMixin):
  45. """
  46. Replica model with custom storage mechanism.
  47. To simplify we use redis cache storage for this demo, but any SQL and NoSQL storage can
  48. be used.
  49. """
  50. CQRS_ID = 'purchase'
  51. CQRS_CUSTOM_SERIALIZATION = True
  52. class Meta:
  53. abstract = True
  54. @classmethod
  55. def cqrs_save(cls, master_data, previous_data=None, sync=False, meta=None):
  56. cache.set('purchase_' + str(master_data['id']), master_data)
  57. return True
  58. @classmethod
  59. def cqrs_delete(cls, master_data, meta=None):
  60. cache.delete('purchase_' + str(master_data['id']))
  61. return True