From: Guillaume Pellerin Date: Thu, 7 Jul 2016 14:26:45 +0000 (+0200) Subject: mv spanning FK to core X-Git-Url: https://git.parisson.com/?a=commitdiff_plain;h=e1490525418c4eb80855b6199bf6881034c236b0;p=mezzo.git mv spanning FK to core --- diff --git a/app/organization/core/related.py b/app/organization/core/related.py new file mode 100644 index 00000000..5b1affbd --- /dev/null +++ b/app/organization/core/related.py @@ -0,0 +1,32 @@ +from django.core import exceptions +from django.db.models.fields.related import ForeignKey +from django.db.utils import ConnectionHandler, ConnectionRouter + +connections = ConnectionHandler() +router = ConnectionRouter() + + +class SpanningForeignKey(ForeignKey): + + def validate(self, value, model_instance): + if self.rel.parent_link: + return + # Call the grandparent rather than the parent to skip validation + super(ForeignKey, self).validate(value, model_instance) + if value is None: + return + + using = router.db_for_read(self.rel.to, instance=model_instance) + qs = self.rel.to._default_manager.using(using).filter( + **{self.rel.field_name: value} + ) + qs = qs.complex_filter(self.get_limit_choices_to()) + if not qs.exists(): + raise exceptions.ValidationError( + self.error_messages['invalid'], + code='invalid', + params={ + 'model': self.rel.to._meta.verbose_name, 'pk': value, + 'field': self.rel.field_name, 'value': value, + }, # 'pk' is included for backwards compatibility + ) diff --git a/app/organization/festival/related.py b/app/organization/festival/related.py deleted file mode 100644 index 5b1affbd..00000000 --- a/app/organization/festival/related.py +++ /dev/null @@ -1,32 +0,0 @@ -from django.core import exceptions -from django.db.models.fields.related import ForeignKey -from django.db.utils import ConnectionHandler, ConnectionRouter - -connections = ConnectionHandler() -router = ConnectionRouter() - - -class SpanningForeignKey(ForeignKey): - - def validate(self, value, model_instance): - if self.rel.parent_link: - return - # Call the grandparent rather than the parent to skip validation - super(ForeignKey, self).validate(value, model_instance) - if value is None: - return - - using = router.db_for_read(self.rel.to, instance=model_instance) - qs = self.rel.to._default_manager.using(using).filter( - **{self.rel.field_name: value} - ) - qs = qs.complex_filter(self.get_limit_choices_to()) - if not qs.exists(): - raise exceptions.ValidationError( - self.error_messages['invalid'], - code='invalid', - params={ - 'model': self.rel.to._meta.verbose_name, 'pk': value, - 'field': self.rel.field_name, 'value': value, - }, # 'pk' is included for backwards compatibility - )