composite.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. import json
  2. from django.core import checks
  3. from django.db.models import NOT_PROVIDED, Field
  4. from django.db.models.expressions import ColPairs
  5. from django.db.models.fields.tuple_lookups import (
  6. TupleExact,
  7. TupleGreaterThan,
  8. TupleGreaterThanOrEqual,
  9. TupleIn,
  10. TupleIsNull,
  11. TupleLessThan,
  12. TupleLessThanOrEqual,
  13. )
  14. from django.utils.functional import cached_property
  15. class AttributeSetter:
  16. def __init__(self, name, value):
  17. setattr(self, name, value)
  18. class CompositeAttribute:
  19. def __init__(self, field):
  20. self.field = field
  21. @property
  22. def attnames(self):
  23. return [field.attname for field in self.field.fields]
  24. def __get__(self, instance, cls=None):
  25. return tuple(getattr(instance, attname) for attname in self.attnames)
  26. def __set__(self, instance, values):
  27. attnames = self.attnames
  28. length = len(attnames)
  29. if values is None:
  30. values = (None,) * length
  31. if not isinstance(values, (list, tuple)):
  32. raise ValueError(f"{self.field.name!r} must be a list or a tuple.")
  33. if length != len(values):
  34. raise ValueError(f"{self.field.name!r} must have {length} elements.")
  35. for attname, value in zip(attnames, values):
  36. setattr(instance, attname, value)
  37. class CompositePrimaryKey(Field):
  38. descriptor_class = CompositeAttribute
  39. def __init__(self, *args, **kwargs):
  40. if (
  41. not args
  42. or not all(isinstance(field, str) for field in args)
  43. or len(set(args)) != len(args)
  44. ):
  45. raise ValueError("CompositePrimaryKey args must be unique strings.")
  46. if len(args) == 1:
  47. raise ValueError("CompositePrimaryKey must include at least two fields.")
  48. if kwargs.get("default", NOT_PROVIDED) is not NOT_PROVIDED:
  49. raise ValueError("CompositePrimaryKey cannot have a default.")
  50. if kwargs.get("db_default", NOT_PROVIDED) is not NOT_PROVIDED:
  51. raise ValueError("CompositePrimaryKey cannot have a database default.")
  52. if kwargs.get("db_column", None) is not None:
  53. raise ValueError("CompositePrimaryKey cannot have a db_column.")
  54. if kwargs.setdefault("editable", False):
  55. raise ValueError("CompositePrimaryKey cannot be editable.")
  56. if not kwargs.setdefault("primary_key", True):
  57. raise ValueError("CompositePrimaryKey must be a primary key.")
  58. if not kwargs.setdefault("blank", True):
  59. raise ValueError("CompositePrimaryKey must be blank.")
  60. self.field_names = args
  61. super().__init__(**kwargs)
  62. def deconstruct(self):
  63. # args is always [] so it can be ignored.
  64. name, path, _, kwargs = super().deconstruct()
  65. return name, path, self.field_names, kwargs
  66. @cached_property
  67. def fields(self):
  68. meta = self.model._meta
  69. return tuple(meta.get_field(field_name) for field_name in self.field_names)
  70. @cached_property
  71. def columns(self):
  72. return tuple(field.column for field in self.fields)
  73. def contribute_to_class(self, cls, name, private_only=False):
  74. super().contribute_to_class(cls, name, private_only=private_only)
  75. cls._meta.pk = self
  76. setattr(cls, self.attname, self.descriptor_class(self))
  77. def get_attname_column(self):
  78. return self.get_attname(), None
  79. def __iter__(self):
  80. return iter(self.fields)
  81. def __len__(self):
  82. return len(self.field_names)
  83. @cached_property
  84. def cached_col(self):
  85. return ColPairs(self.model._meta.db_table, self.fields, self.fields, self)
  86. def get_col(self, alias, output_field=None):
  87. if alias == self.model._meta.db_table and (
  88. output_field is None or output_field == self
  89. ):
  90. return self.cached_col
  91. return ColPairs(alias, self.fields, self.fields, output_field)
  92. def get_pk_value_on_save(self, instance):
  93. values = []
  94. for field in self.fields:
  95. value = field.value_from_object(instance)
  96. if value is None:
  97. value = field.get_pk_value_on_save(instance)
  98. values.append(value)
  99. return tuple(values)
  100. def _check_field_name(self):
  101. if self.name == "pk":
  102. return []
  103. return [
  104. checks.Error(
  105. "'CompositePrimaryKey' must be named 'pk'.",
  106. obj=self,
  107. id="fields.E013",
  108. )
  109. ]
  110. def value_to_string(self, obj):
  111. values = []
  112. vals = self.value_from_object(obj)
  113. for field, value in zip(self.fields, vals):
  114. obj = AttributeSetter(field.attname, value)
  115. values.append(field.value_to_string(obj))
  116. return json.dumps(values, ensure_ascii=False)
  117. def to_python(self, value):
  118. if isinstance(value, str):
  119. # Assume we're deserializing.
  120. vals = json.loads(value)
  121. value = [
  122. field.to_python(val)
  123. for field, val in zip(self.fields, vals, strict=True)
  124. ]
  125. return value
  126. CompositePrimaryKey.register_lookup(TupleExact)
  127. CompositePrimaryKey.register_lookup(TupleGreaterThan)
  128. CompositePrimaryKey.register_lookup(TupleGreaterThanOrEqual)
  129. CompositePrimaryKey.register_lookup(TupleLessThan)
  130. CompositePrimaryKey.register_lookup(TupleLessThanOrEqual)
  131. CompositePrimaryKey.register_lookup(TupleIn)
  132. CompositePrimaryKey.register_lookup(TupleIsNull)
  133. def unnest(fields):
  134. result = []
  135. for field in fields:
  136. if isinstance(field, CompositePrimaryKey):
  137. result.extend(field.fields)
  138. else:
  139. result.append(field)
  140. return result