0

I have the following in my app:

class University(models.Model):
    ...
    sister_university = models.OneToOneField('self', 
                        related_name = 
                        'university_sister_university', 
                        blank=True, null=True, 
                        on_delete=models.SET_NULL)

As it is, under the Django Admin site, I’m able to select University A as the sister_university of University A (itself). Is it possible to enforce some sort of a rule at the database level so a university object can never be its own sister_university?

Alternatively, is there a better way of accomplishing what I’m trying to do?

Joe
  • 173
  • 10
  • @BearBrown They’re two different questions. Same example code but the previous question asks whether *uniqueness* can be assured and the second question (this question) asks if I can prevent an object from referring to itself. So please don’t close this. Thanks! – Joe May 15 '18 at 20:37
  • you just added info about admin but unique for sister is present in two question – Brown Bear May 15 '18 at 20:42
  • @BearBrown Maybe, I’m missing something. Can you please point me to where this question says “unique for sister”? I’d be happy to correct it. – Joe May 15 '18 at 20:47
  • @BearBrown The main point of this question is preventing an object from referring to itself, which is not an issue raised in the previous question. – Joe May 15 '18 at 20:48
  • to exclude the conflict situation in next time, look on example in the top of the question: [statement-to-django-queryset](https://stackoverflow.com/questions/50286057/how-can-i-convert-this-sql-statement-to-django-queryset) – Brown Bear May 15 '18 at 21:02
  • @BearBrown That’s helpful. I’ll be sure to do that next time. Thanks – Joe May 15 '18 at 21:06

2 Answers2

0

What you want is a check constraint, something like:

alter table university
add constraint chk_non_self_ref check (id <> sister_university_id);

I'm not aware of a way to define this in Django models (but I'm guessing you can add it to a migration).

thebjorn
  • 26,297
  • 11
  • 96
  • 138
0

At the model level, you can override the clean() method of your model to implement that check every time a University instance is saved.

def clean(self):

    if self.sister_university.id == self.id:
        raise ValidationError('A university object can never be its own sister_university.')
codeandfire
  • 445
  • 2
  • 9