我需要驗證模型字段是否爲小寫唯一,但實際上並未以小寫字母保存模型字段;例如如果某人已經使用了用戶名'david',那麼用戶名'David'將不可用。我嘗試了各種各樣的東西,並最終結束了以下工作:將模型字段驗證爲小寫唯一
def _perform_unique_checks(self, unique_checks):
errors = {}
for model_class, unique_check in unique_checks:
lookup_kwargs = {}
for field_name in unique_check:
f = self._meta.get_field(field_name)
lookup_value = getattr(self, f.attname)
if lookup_value is None:
continue
if f.primary_key and not self._state.adding:
continue
lookup_kwargs[str(field_name)] = lookup_value
if len(unique_check) != len(lookup_kwargs):
continue
if 'username' in lookup_kwargs:
lookup_kwargs['username'] = lookup_kwargs['username'].lower()
qs = model_class._default_manager.filter(**lookup_kwargs)
model_class_pk = self._get_pk_val(model_class._meta)
if not self._state.adding and model_class_pk is not None:
qs = qs.exclude(pk=model_class_pk)
if qs.exists():
if len(unique_check) == 1:
key = unique_check[0]
else:
key = NON_FIELD_ERRORS
errors.setdefault(key, []).append(
self.unique_error_message(model_class, unique_check))
......它工作,但感覺有點複雜的我。我想知道是否有更簡潔的方法來實現這一目標?