1 | from django.db import models
|
---|
2 | from django.db.models import Q
|
---|
3 |
|
---|
4 |
|
---|
5 | class Measure(models.Model):
|
---|
6 |
|
---|
7 | id = models.AutoField(
|
---|
8 | primary_key=True,
|
---|
9 | verbose_name="Key",
|
---|
10 | )
|
---|
11 | code = models.CharField(
|
---|
12 | max_length=5,
|
---|
13 | unique=True,
|
---|
14 | verbose_name="Code",
|
---|
15 | error_messages={"unique": "Err msg."},
|
---|
16 | )
|
---|
17 |
|
---|
18 | def __str__(self):
|
---|
19 | return self.code
|
---|
20 |
|
---|
21 |
|
---|
22 | class MyModel(models.Model):
|
---|
23 |
|
---|
24 | id = models.BigAutoField(primary_key=True, editable=False)
|
---|
25 | name = models.CharField(max_length=1000, verbose_name="Name")
|
---|
26 | measure = models.ForeignKey(
|
---|
27 | Measure,
|
---|
28 | related_name="mymodel_measure",
|
---|
29 | on_delete=models.SET_NULL,
|
---|
30 | null=True,
|
---|
31 | blank=True,
|
---|
32 | verbose_name="Measure",
|
---|
33 | )
|
---|
34 |
|
---|
35 | def __str__(self):
|
---|
36 | return self.name
|
---|
37 |
|
---|
38 | class Meta:
|
---|
39 | constraints = [
|
---|
40 | models.UniqueConstraint(
|
---|
41 | fields=["name"],
|
---|
42 | name="mymodel_unique_name_measure_null",
|
---|
43 | condition=Q(measure__isnull=True),
|
---|
44 | violation_error_message="Error message for null",
|
---|
45 | ),
|
---|
46 | models.UniqueConstraint(
|
---|
47 | fields=["name", "measure"],
|
---|
48 | name="mymodel_unique_name_measure_not_null",
|
---|
49 | condition=Q(measure__isnull=False),
|
---|
50 | violation_error_message="Error message for not null",
|
---|
51 | ),
|
---|
52 | ]
|
---|