How to use 'django unique_together' in Python

Every line of 'django unique_together' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your Python code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
43def unique_together_constraint(model, instance):
44 if not instance._meta.unique_together:
45 return
46 error_fields = []
47 for unique_fields in instance._meta.unique_together:
48 check = {}
49 for field_name in unique_fields:
50 if not get_field(instance, field_name).primary_key:
51 check[field_name] = getattr(instance, field_name)
52 if all(e is None for e in check.values()):
53 continue
54
55 if model._default_manager.filter(**check).exists():
56 error_fields.extend([
57 get_field(instance, field_name)
58 for field_name in unique_fields
59 ])
60 if error_fields:
61 raise InvalidConstraint(error_fields)
104def test_pointing_to_m2m_field(self):
105 class Model(models.Model):
106 m2m = models.ManyToManyField('self')
107
108 class Meta:
109 index_together = [['m2m']]
110
111 self.assertEqual(Model.check(), [
112 Error(
113 "'index_together' refers to a ManyToManyField 'm2m', but "
114 "ManyToManyFields are not permitted in 'index_together'.",
115 obj=Model,
116 id='models.E013',
117 ),
118 ])

Related snippets