related_field.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. # -*- coding: utf-8 -*-
  2. from .const import get_join
  3. class RelatedField:
  4. # 举例:
  5. # customer_name = fields.Char(string='客户', related='customer_id.name')
  6. # 则:
  7. # for field, info in self._fields.items():
  8. # info.related: ('customer','name')
  9. # info.related_field: 'archives.customer.name'
  10. # info.depends: ('customer_id.name',)
  11. def __init__(self, left_alias, related_info):
  12. self._left_alias = left_alias
  13. self._related_info = related_info
  14. self._related_field, self._related_model_field = RelatedField._get_related_info(related_info)
  15. self._related_model = None
  16. return
  17. def __str__(self):
  18. _f = '<RelatedField== left alias:{}, related model:{},related field:{},related model field:{}>'
  19. return _f.format(self._left_alias, self._related_model, self._related_field, self._related_model_field)
  20. def get_related_field(self):
  21. return self._related_field
  22. def get_field_in_related_model(self):
  23. return self._related_model_field
  24. def set_related_model(self, related_model):
  25. self._related_model = related_model
  26. return
  27. def get_related_alias(self):
  28. return self._related_model.get_alias()
  29. def get_join(self):
  30. return get_join(self._left_alias, self._related_field, self._related_model.get_table(),
  31. self._related_model.get_alias(), 'id')
  32. def get_selected_field(self):
  33. return '{}.{}'.format(self._related_model.get_alias(), self._related_model_field)
  34. @staticmethod
  35. def _get_related_info(related_field):
  36. # print('_get_related_info, related_field:', related_field)
  37. if not related_field:
  38. return '', ''
  39. pair = related_field.split('.')
  40. if len(pair) == 2:
  41. return pair
  42. return '', ''