I have two models like so:
class Group(...):
pass
class Identifier(...):
value = models.CharField(...)
group = models.ForeignKey('Group', ..., related_named = 'identifiers')
How can I:
- restrict a
Groupto only have at most 4Identifiers? - Ensure that any combination of up to 4
Identifiers(the value of the identifier) is unique across allGroups?
For part 2, here is an example of the flattened Groups table:
row | id__0__val | id__1__val | id__2__val | id__3__val
--- | ---------- | ---------- | ---------- | ----------
0 | abc | 123 | xyz | 456
1 | abc | 123 | xyz | - <-- valid (nulls are okay)
2 | 123 | abc | xyz | 456 <-- invalid (same combo as row 0)
Previously I have tried (something like) this, but it seems messy, has limited functionality, and I'm not sure it will even work:
class Group(...):
id__0 = models.OneToOneField('Identifier', blank = True, null = True, ...)
id__1 = models.OneToOneField('Identifier', blank = True, null = True, ...)
id__2 = models.OneToOneField('Identifier', blank = True, null = True, ...)
id__3 = models.OneToOneField('Identifier', blank = True, null = True, ...)
class Meta:
unique_together = ('id__0__value', 'id__1__value', 'id__2__value', 'id__3__value')
What is a better way to handle this constraint?
from Django - Unique Collection of Foreign Keys Constraint
No comments:
Post a Comment