serhattsnmz
serhattsnmz

Reputation: 177

Peewee one-to-one connection

I am trying to define two table which has relations one-to-one each other. But I couldn't do that.

My models are like that:

class Model1(BaseModel):
    field1 = TextField()

class Model2(BaseModel):
    rel_model = ForeignKeyField(Model1, backref="model1", unique=True)
    field2 = TextField

This models create one-to-many relations.

Upvotes: 2

Views: 1477

Answers (1)

coleifer
coleifer

Reputation: 26245

Peewee has no concept of 1-to-1 beyond a foreign-key with a unique constraint, which is what you have declared.

Just expose it as a property on the back-reference if that's what you want:

class Model1(BaseModel):
    @property
    def model2(self):
        return self.model2_set.get()

class Model2(BaseModel):
    model1 = ForeignKeyField(Model1, unique=True)

You've got your backref backwards in your example, by the way - it is a backref of "model2" instances.

Upvotes: 5

Related Questions