Ticket #11702: related.patch

File related.patch, 1.8 KB (added by marcosmoyano, 5 years ago)

django.db.fields.related patch

  • django/db/models/fields/related.py

     
    1212from django.utils.functional import curry
    1313from django.core import exceptions
    1414from django import forms
     15from django.core.exceptions import FieldError
    1516
    1617
    1718RECURSIVE_RELATIONSHIP_CONSTANT = 'self'
     
    752753class ForeignKey(RelatedField, Field):
    753754    empty_strings_allowed = False
    754755    default_error_messages = {
    755         'invalid': _('Model %(model)s with pk %(pk)r does not exist.')
     756        'invalid': _('Model %(model)s with pk %(pk)r does not exist.'),
     757        'improperly_configured': _('Field \'%(field)s\' under model \'%(model)s\' must have a unique=True constraint.'),
    756758    }
    757759    description = _("Foreign Key (type determined by related field)")
    758760    def __init__(self, to, to_field=None, rel_class=ManyToOneRel, **kwargs):
     
    766768            # the to_field during FK construction. It won't be guaranteed to
    767769            # be correct until contribute_to_class is called. Refs #12190.
    768770            to_field = to_field or (to._meta.pk and to._meta.pk.name)
     771            # Make sure we have a unique=True constraint in the ForeignKey field if to_field is set.
     772            if to_field:
     773                try:
     774                    assert to._meta.get_field(to_field).unique, \
     775                           "Field %s under model %s must have a unique=True constraint." % (to_field, to.__class__.__name__)
     776                except:
     777                    raise FieldError(self.default_error_messages['improperly_configured'] % {
     778                        'field': to_field, 'model': to._meta.object_name})
     779
    769780        kwargs['verbose_name'] = kwargs.get('verbose_name', None)
    770781
    771782        kwargs['rel'] = rel_class(to, to_field,
Back to Top