| 1 |
""" |
| 2 |
Helper functions for mapping model fields to a dictionary of default |
| 3 |
keyword arguments that should be used for their equivalent serializer fields. |
| 4 |
""" |
| 5 |
import inspect |
| 6 |
|
| 7 |
from django.core import validators |
| 8 |
from django.db import models |
| 9 |
from django.utils.text import capfirst |
| 10 |
|
| 11 |
from rest_framework.compat import postgres_fields |
| 12 |
from rest_framework.validators import UniqueValidator |
| 13 |
|
| 14 |
NUMERIC_FIELD_TYPES = ( |
| 15 |
models.IntegerField, models.FloatField, models.DecimalField, models.DurationField, |
| 16 |
) |
| 17 |
|
| 18 |
|
| 19 |
class ClassLookupDict: |
| 20 |
""" |
| 21 |
Takes a dictionary with classes as keys. |
| 22 |
Lookups against this object will traverses the object's inheritance |
| 23 |
hierarchy in method resolution order, and returns the first matching value |
| 24 |
from the dictionary or raises a KeyError if nothing matches. |
| 25 |
""" |
| 26 |
def __init__(self, mapping): |
| 27 |
self.mapping = mapping |
| 28 |
|
| 29 |
def __getitem__(self, key): |
| 30 |
if hasattr(key, '_proxy_class'): |
| 31 |
# Deal with proxy classes. Ie. BoundField behaves as if it |
| 32 |
# is a Field instance when using ClassLookupDict. |
| 33 |
base_class = key._proxy_class |
| 34 |
else: |
| 35 |
base_class = key.__class__ |
| 36 |
|
| 37 |
for cls in inspect.getmro(base_class): |
| 38 |
if cls in self.mapping: |
| 39 |
return self.mapping[cls] |
| 40 |
raise KeyError('Class %s not found in lookup.' % base_class.__name__) |
| 41 |
|
| 42 |
def __setitem__(self, key, value): |
| 43 |
self.mapping[key] = value |
| 44 |
|
| 45 |
|
| 46 |
def needs_label(model_field, field_name): |
| 47 |
""" |
| 48 |
Returns `True` if the label based on the model's verbose name |
| 49 |
is not equal to the default label it would have based on it's field name. |
| 50 |
""" |
| 51 |
default_label = field_name.replace('_', ' ').capitalize() |
| 52 |
return capfirst(model_field.verbose_name) != default_label |
| 53 |
|
| 54 |
|
| 55 |
def get_detail_view_name(model): |
| 56 |
""" |
| 57 |
Given a model class, return the view name to use for URL relationships |
| 58 |
that refer to instances of the model. |
| 59 |
""" |
| 60 |
return '%(model_name)s-detail' % { |
| 61 |
'model_name': model._meta.object_name.lower() |
| 62 |
} |
| 63 |
|
| 64 |
|
| 65 |
def get_unique_validators(field_name, model_field): |
| 66 |
""" |
| 67 |
Returns a list of UniqueValidators that should be applied to the field. |
| 68 |
""" |
| 69 |
field_set = {field_name} |
| 70 |
conditions = { |
| 71 |
c.condition |
| 72 |
for c in model_field.model._meta.constraints |
| 73 |
if isinstance(c, models.UniqueConstraint) and set(c.fields) == field_set |
| 74 |
} |
| 75 |
if getattr(model_field, 'unique', False): |
| 76 |
conditions.add(None) |
| 77 |
if not conditions: |
| 78 |
return |
| 79 |
unique_error_message = get_unique_error_message(model_field) |
| 80 |
queryset = model_field.model._default_manager |
| 81 |
for condition in conditions: |
| 82 |
yield UniqueValidator( |
| 83 |
queryset=queryset if condition is None else queryset.filter(condition), |
| 84 |
message=unique_error_message |
| 85 |
) |
| 86 |
|
| 87 |
|
| 88 |
def get_field_kwargs(field_name, model_field): |
| 89 |
""" |
| 90 |
Creates a default instance of a basic non-relational field. |
| 91 |
""" |
| 92 |
kwargs = {} |
| 93 |
validator_kwarg = list(model_field.validators) |
| 94 |
|
| 95 |
# The following will only be used by ModelField classes. |
| 96 |
# Gets removed for everything else. |
| 97 |
kwargs['model_field'] = model_field |
| 98 |
|
| 99 |
if model_field.verbose_name and needs_label(model_field, field_name): |
| 100 |
kwargs['label'] = capfirst(model_field.verbose_name) |
| 101 |
|
| 102 |
if model_field.help_text: |
| 103 |
kwargs['help_text'] = model_field.help_text |
| 104 |
|
| 105 |
max_digits = getattr(model_field, 'max_digits', None) |
| 106 |
if max_digits is not None: |
| 107 |
kwargs['max_digits'] = max_digits |
| 108 |
|
| 109 |
decimal_places = getattr(model_field, 'decimal_places', None) |
| 110 |
if decimal_places is not None: |
| 111 |
kwargs['decimal_places'] = decimal_places |
| 112 |
|
| 113 |
if isinstance(model_field, models.SlugField): |
| 114 |
kwargs['allow_unicode'] = model_field.allow_unicode |
| 115 |
|
| 116 |
if isinstance(model_field, models.TextField) and not model_field.choices or \ |
| 117 |
(postgres_fields and isinstance(model_field, postgres_fields.JSONField)) or \ |
| 118 |
(hasattr(models, 'JSONField') and isinstance(model_field, models.JSONField)): |
| 119 |
kwargs['style'] = {'base_template': 'textarea.html'} |
| 120 |
|
| 121 |
if model_field.null: |
| 122 |
kwargs['allow_null'] = True |
| 123 |
|
| 124 |
if model_field.choices: |
| 125 |
kwargs['choices'] = model_field.choices |
| 126 |
|
| 127 |
if isinstance(model_field, models.AutoField) or not model_field.editable: |
| 128 |
# If this field is read-only, then return early. |
| 129 |
# Further keyword arguments are not valid. |
| 130 |
kwargs['read_only'] = True |
| 131 |
return kwargs |
| 132 |
|
| 133 |
if model_field.has_default() or model_field.blank or model_field.null: |
| 134 |
kwargs['required'] = False |
| 135 |
|
| 136 |
if model_field.blank and (isinstance(model_field, (models.CharField, models.TextField))): |
| 137 |
kwargs['allow_blank'] = True |
| 138 |
|
| 139 |
if not model_field.blank and (postgres_fields and isinstance(model_field, postgres_fields.ArrayField)): |
| 140 |
kwargs['allow_empty'] = False |
| 141 |
|
| 142 |
if isinstance(model_field, models.FilePathField): |
| 143 |
kwargs['path'] = model_field.path |
| 144 |
|
| 145 |
if model_field.match is not None: |
| 146 |
kwargs['match'] = model_field.match |
| 147 |
|
| 148 |
if model_field.recursive is not False: |
| 149 |
kwargs['recursive'] = model_field.recursive |
| 150 |
|
| 151 |
if model_field.allow_files is not True: |
| 152 |
kwargs['allow_files'] = model_field.allow_files |
| 153 |
|
| 154 |
if model_field.allow_folders is not False: |
| 155 |
kwargs['allow_folders'] = model_field.allow_folders |
| 156 |
|
| 157 |
if not model_field.choices: |
| 158 |
# Ensure that max_value is passed explicitly as a keyword arg, |
| 159 |
# rather than as a validator. |
| 160 |
max_value = next(( |
| 161 |
validator.limit_value for validator in validator_kwarg |
| 162 |
if isinstance(validator, validators.MaxValueValidator) |
| 163 |
), None) |
| 164 |
if max_value is not None and isinstance(model_field, NUMERIC_FIELD_TYPES): |
| 165 |
kwargs['max_value'] = max_value |
| 166 |
validator_kwarg = [ |
| 167 |
validator for validator in validator_kwarg |
| 168 |
if not isinstance(validator, validators.MaxValueValidator) |
| 169 |
] |
| 170 |
|
| 171 |
# Ensure that min_value is passed explicitly as a keyword arg, |
| 172 |
# rather than as a validator. |
| 173 |
min_value = next(( |
| 174 |
validator.limit_value for validator in validator_kwarg |
| 175 |
if isinstance(validator, validators.MinValueValidator) |
| 176 |
), None) |
| 177 |
if min_value is not None and isinstance(model_field, NUMERIC_FIELD_TYPES): |
| 178 |
kwargs['min_value'] = min_value |
| 179 |
validator_kwarg = [ |
| 180 |
validator for validator in validator_kwarg |
| 181 |
if not isinstance(validator, validators.MinValueValidator) |
| 182 |
] |
| 183 |
|
| 184 |
# URLField does not need to include the URLValidator argument, |
| 185 |
# as it is explicitly added in. |
| 186 |
if isinstance(model_field, models.URLField): |
| 187 |
validator_kwarg = [ |
| 188 |
validator for validator in validator_kwarg |
| 189 |
if not isinstance(validator, validators.URLValidator) |
| 190 |
] |
| 191 |
|
| 192 |
# EmailField does not need to include the validate_email argument, |
| 193 |
# as it is explicitly added in. |
| 194 |
if isinstance(model_field, models.EmailField): |
| 195 |
validator_kwarg = [ |
| 196 |
validator for validator in validator_kwarg |
| 197 |
if validator is not validators.validate_email |
| 198 |
] |
| 199 |
|
| 200 |
# SlugField do not need to include the 'validate_slug' argument, |
| 201 |
if isinstance(model_field, models.SlugField): |
| 202 |
validator_kwarg = [ |
| 203 |
validator for validator in validator_kwarg |
| 204 |
if validator is not validators.validate_slug |
| 205 |
] |
| 206 |
|
| 207 |
# IPAddressField does not need to include the IP address validators, |
| 208 |
# as it adds its own based on the 'protocol' argument. |
| 209 |
if isinstance(model_field, models.GenericIPAddressField): |
| 210 |
kwargs['protocol'] = model_field.protocol |
| 211 |
validator_kwarg = [ |
| 212 |
validator for validator in validator_kwarg |
| 213 |
if validator not in ( |
| 214 |
validators.validate_ipv46_address, |
| 215 |
validators.validate_ipv4_address, |
| 216 |
validators.validate_ipv6_address, |
| 217 |
) |
| 218 |
] |
| 219 |
# Our decimal validation is handled in the field code, not validator code. |
| 220 |
if isinstance(model_field, models.DecimalField): |
| 221 |
validator_kwarg = [ |
| 222 |
validator for validator in validator_kwarg |
| 223 |
if not isinstance(validator, validators.DecimalValidator) |
| 224 |
] |
| 225 |
|
| 226 |
# Ensure that max_length is passed explicitly as a keyword arg, |
| 227 |
# rather than as a validator. |
| 228 |
max_length = getattr(model_field, 'max_length', None) |
| 229 |
if max_length is not None and (isinstance(model_field, (models.CharField, models.TextField, models.FileField))): |
| 230 |
kwargs['max_length'] = max_length |
| 231 |
validator_kwarg = [ |
| 232 |
validator for validator in validator_kwarg |
| 233 |
if not isinstance(validator, validators.MaxLengthValidator) |
| 234 |
] |
| 235 |
|
| 236 |
# Ensure that min_length is passed explicitly as a keyword arg, |
| 237 |
# rather than as a validator. |
| 238 |
min_length = next(( |
| 239 |
validator.limit_value for validator in validator_kwarg |
| 240 |
if isinstance(validator, validators.MinLengthValidator) |
| 241 |
), None) |
| 242 |
if min_length is not None and isinstance(model_field, models.CharField): |
| 243 |
kwargs['min_length'] = min_length |
| 244 |
validator_kwarg = [ |
| 245 |
validator for validator in validator_kwarg |
| 246 |
if not isinstance(validator, validators.MinLengthValidator) |
| 247 |
] |
| 248 |
|
| 249 |
validator_kwarg += get_unique_validators(field_name, model_field) |
| 250 |
|
| 251 |
if validator_kwarg: |
| 252 |
kwargs['validators'] = validator_kwarg |
| 253 |
|
| 254 |
return kwargs |
| 255 |
|
| 256 |
|
| 257 |
def get_relation_kwargs(field_name, relation_info): |
| 258 |
""" |
| 259 |
Creates a default instance of a flat relational field. |
| 260 |
""" |
| 261 |
model_field, related_model, to_many, to_field, has_through_model, reverse = relation_info |
| 262 |
kwargs = { |
| 263 |
'queryset': related_model._default_manager, |
| 264 |
'view_name': get_detail_view_name(related_model) |
| 265 |
} |
| 266 |
|
| 267 |
if to_many: |
| 268 |
kwargs['many'] = True |
| 269 |
|
| 270 |
if to_field: |
| 271 |
kwargs['to_field'] = to_field |
| 272 |
|
| 273 |
limit_choices_to = model_field and model_field.get_limit_choices_to() |
| 274 |
if limit_choices_to: |
| 275 |
if not isinstance(limit_choices_to, models.Q): |
| 276 |
limit_choices_to = models.Q(**limit_choices_to) |
| 277 |
kwargs['queryset'] = kwargs['queryset'].filter(limit_choices_to) |
| 278 |
|
| 279 |
if has_through_model: |
| 280 |
kwargs['read_only'] = True |
| 281 |
kwargs.pop('queryset', None) |
| 282 |
|
| 283 |
if model_field: |
| 284 |
if model_field.verbose_name and needs_label(model_field, field_name): |
| 285 |
kwargs['label'] = capfirst(model_field.verbose_name) |
| 286 |
help_text = model_field.help_text |
| 287 |
if help_text: |
| 288 |
kwargs['help_text'] = help_text |
| 289 |
if not model_field.editable: |
| 290 |
kwargs['read_only'] = True |
| 291 |
kwargs.pop('queryset', None) |
| 292 |
if model_field.null: |
| 293 |
kwargs['allow_null'] = True |
| 294 |
if kwargs.get('read_only', False): |
| 295 |
# If this field is read-only, then return early. |
| 296 |
# No further keyword arguments are valid. |
| 297 |
return kwargs |
| 298 |
|
| 299 |
if model_field.has_default() or model_field.blank or model_field.null: |
| 300 |
kwargs['required'] = False |
| 301 |
if model_field.validators: |
| 302 |
kwargs['validators'] = model_field.validators |
| 303 |
if getattr(model_field, 'unique', False): |
| 304 |
validator = UniqueValidator( |
| 305 |
queryset=model_field.model._default_manager, |
| 306 |
message=get_unique_error_message(model_field)) |
| 307 |
kwargs['validators'] = kwargs.get('validators', []) + [validator] |
| 308 |
if to_many and not model_field.blank: |
| 309 |
kwargs['allow_empty'] = False |
| 310 |
|
| 311 |
return kwargs |
| 312 |
|
| 313 |
|
| 314 |
def get_nested_relation_kwargs(relation_info): |
| 315 |
kwargs = {'read_only': True} |
| 316 |
if relation_info.to_many: |
| 317 |
kwargs['many'] = True |
| 318 |
return kwargs |
| 319 |
|
| 320 |
|
| 321 |
def get_url_kwargs(model_field): |
| 322 |
return { |
| 323 |
'view_name': get_detail_view_name(model_field) |
| 324 |
} |
| 325 |
|
| 326 |
|
| 327 |
def get_unique_error_message(model_field): |
| 328 |
unique_error_message = model_field.error_messages.get('unique', None) |
| 329 |
if unique_error_message: |
| 330 |
unique_error_message = unique_error_message % { |
| 331 |
'model_name': model_field.model._meta.verbose_name, |
| 332 |
'field_label': model_field.verbose_name |
| 333 |
} |
| 334 |
return unique_error_message |