'Peewee Composite Primary Key - How can I avoid duplicates if fields are reversed?

I have a simple Person model and a Relationship model that links two people together that form a relationship.

from peewee import *

db = SqliteDatabase(':memory:')

class BaseModel(Model):
    class Meta:
        database = db

class Person(BaseModel):
    name = CharField()

class Relationship(BaseModel):
    p1 = ForeignKeyField(Person)
    p2 = ForeignKeyField(Person)

db.create_tables([Person, Relationship])      

Is there any way to make sure that there can only be one Relationship instance between two Person instances, even if p1 and p2 are reversed?

Edit:

I found this solution using raw SQL.

db.execute_sql('CREATE UNIQUE INDEX unique_ix ON Relationship (MIN(p1_id, p2_id), MAX(p1_id, p2_id))')

Or:

Relationship.add_index(SQL('CREATE UNIQUE INDEX unique_ix ON Relationship (MIN(p1_id, p2_id), MAX(p1_id, p2_id))'))


Solution 1:[1]

You might be able to make a unique constraint on something like (p1 xor p2) (you will need additional data, but this should give you an idea) if your database provides that.

Alternatively you could create a unique index on min(p1, p2), max(p1, p2)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 coleifer