| 7 | |
| 8 | |
| 9 | {{{ |
| 10 | # models.py |
| 11 | class DTOManager(models.Manager): |
| 12 | @sync_to_async |
| 13 | def filter(self, *args, **kwargs) -> list[BaseModel]: |
| 14 | return [self._dto_mapper(i) for i in self.model.objects.filter(*args, **kwargs)] |
| 15 | |
| 16 | @sync_to_async |
| 17 | def get(self, *args, **kwargs) -> BaseModel: |
| 18 | try: |
| 19 | return self._dto_mapper(self.model.objects.get(*args, **kwargs)) |
| 20 | except self.model.DoesNotExist: |
| 21 | raise ObjectNotFound(f"{self.model.__name__} not found") |
| 22 | |
| 23 | class Hotel(models.Model): |
| 24 | id = models.UUIDField(primary_key=True, editable=False) |
| 25 | coordinates = models.PointField(null=True) |
| 26 | |
| 27 | dto_objects = DTOManager(dto_mapper=lambda hotel: HotelDTO(**hotel.curated_data) if hotel else None) |
| 28 | objects = models.Manager() |
| 29 | |
| 30 | # services.py |
| 31 | hotels = await Hotel.dto_objects.filter(id=12) |
| 32 | }}} |