简体   繁体   中英

In Django, for a OneToOne relationship between two objects of the same class, can an object be prevented from referring to itself at the db level?

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?

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).

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.')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM