Thursday, 29 July 2021

Django - Unique Collection of Foreign Keys Constraint

I have two models like so:

class Group(...):
    pass

class Identifier(...):
    value = models.CharField(...)
    group = models.ForeignKey('Group', ..., related_named = 'identifiers')

How can I:

  1. restrict a Group to only have at most 4 Identifiers?
  2. Ensure that any combination of up to 4 Identifiers (the value of the identifier) is unique across all Groups?

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