1
0
mirror of https://github.com/django/django.git synced 2025-10-31 09:41:08 +00:00

[1.9.x] Fixed #25535 -- Made ForeignObject checks less strict.

Check that the foreign object `from_fields` are a subset of any unique
constraints on the foreign model.

Backport of 80dac8c33e and
c7aff31397 from master
This commit is contained in:
Antoine Catton
2015-10-09 10:55:19 -06:00
committed by Tim Graham
parent aa0a3b680e
commit 38d6e1e2ad
4 changed files with 154 additions and 12 deletions

View File

@@ -473,22 +473,35 @@ class ForeignObject(RelatedField):
if not self.foreign_related_fields:
return []
has_unique_field = any(rel_field.unique
for rel_field in self.foreign_related_fields)
if not has_unique_field and len(self.foreign_related_fields) > 1:
unique_foreign_fields = {
frozenset([f.name])
for f in self.remote_field.model._meta.get_fields()
if getattr(f, 'unique', False)
}
unique_foreign_fields.update({
frozenset(ut)
for ut in self.remote_field.model._meta.unique_together
})
foreign_fields = {f.name for f in self.foreign_related_fields}
has_unique_constraint = any(u <= foreign_fields for u in unique_foreign_fields)
if not has_unique_constraint and len(self.foreign_related_fields) > 1:
field_combination = ', '.join("'%s'" % rel_field.name
for rel_field in self.foreign_related_fields)
model_name = self.remote_field.model.__name__
return [
checks.Error(
"None of the fields %s on model '%s' have a unique=True constraint."
"No subset of the fields %s on model '%s' is unique."
% (field_combination, model_name),
hint=None,
hint=(
"Add unique=True on any of those fields or add at "
"least a subset of them to a unique_together constraint."
),
obj=self,
id='fields.E310',
)
]
elif not has_unique_field:
elif not has_unique_constraint:
field_name = self.foreign_related_fields[0].name
model_name = self.remote_field.model.__name__
return [