Django

Code

Ticket #7042: t7042_r8472_patch.diff

File t7042_r8472_patch.diff, 2.3 kB (added by clamothe, 5 months ago)

Adds model validation to check that unique = True is not set in ManyToManyFields?. Also contains invalid_model tests to test for the validation.

  • a/django/core/management/validation.py

    old new  
    110110                # so skip the next section 
    111111                if isinstance(f.rel.to, (str, unicode)): 
    112112                    continue 
     113             
     114            # Check that the field is not set to unique.  ManyToManyFields do not support unique. 
     115            if f.unique: 
     116                e.add(opts, "ManyToManyFields cannot be unique.  Remove the unique argument on '%s'." % f.name) 
     117             
    113118            if getattr(f.rel, 'through', None) is not None: 
    114119                if hasattr(f.rel, 'through_model'): 
    115120                    from_model, to_model = cls, f.rel.to 
  • a/tests/modeltests/invalid_models/models.py

    old new  
    177177    fk1 = models.ForeignKey('AbstractModel') 
    178178    fk2 = models.ManyToManyField('AbstractModel') 
    179179     
     180class UniqueM2M(models.Model): 
     181    """ Model to test for unique ManyToManyFields, which are invalid. """ 
     182    unique_people = models.ManyToManyField( Person, unique=True ) 
     183     
    180184model_errors = """invalid_models.fielderrors: "charfield": CharFields require a "max_length" attribute. 
    181185invalid_models.fielderrors: "decimalfield": DecimalFields require a "decimal_places" attribute. 
    182186invalid_models.fielderrors: "decimalfield": DecimalFields require a "max_digits" attribute. 
     
    271275invalid_models.personselfrefm2mexplicit: Many-to-many fields with intermediate tables cannot be symmetrical. 
    272276invalid_models.abstractrelationmodel: 'fk1' has a relation with model AbstractModel, which has either not been installed or is abstract. 
    273277invalid_models.abstractrelationmodel: 'fk2' has an m2m relation with model AbstractModel, which has either not been installed or is abstract. 
     278invalid_models.uniquem2m: ManyToManyFields cannot be unique.  Remove the unique argument on 'unique_people'. 
    274279"""