Search code examples
pythonforeign-keyspeewee

peewee: Get a single model instead of SelectQuery when back-referencing a foreign key


I am struggling a bit with back-referencing foreign keys in peewee. Consider the following code:

import peewee as pw

db = pw.SqliteDatabase(':memory:')

class Parent(pw.Model):
    name = pw.CharField()

    class Meta:
        database = db


class Child(pw.Model):
    name = pw.CharField()
    parent = pw.ForeignKeyField(Parent, related_name="kid")

    class Meta:
        database = db

db.create_tables([Parent, Child])

bob = Parent.create(name="Bob")
alice = Child.create(name="Alice", parent=bob)

Getting access to Bob's children can be done with bob.kid, which would give me a SelectQuery. By design, however, I know that any Parent can only have a single Child. Accessing that child could then be done with bob.kid[0].

I would like to be able to access a Child from a Parent by simply calling bob.kid and not bob.kid[0]. Can this be achieved without modifying the Parent class further?


Solution

  • You can just add a property.

    By default back-refs are 0..N, so best represented by a select query.


    Example:

    class Parent(pw.Model):
        name = pw.CharField()
    
        class Meta:
            database = db
    
        @property
        def kid(self):
            return self.children.get()
    
    
    class Child(pw.Model):
        name = pw.CharField()
        parent = pw.ForeignKeyField(Parent, related_name="children")
    
        class Meta:
            database = db
    

    Tip:

    If the foreign key is really a one-to-one you could add a UNIQUE constraint on the foreign key.