many-to-many with self

142 views
Skip to first unread message

Tim Shaffer

unread,
May 4, 2017, 2:47:05 PM5/4/17
to peewee-orm
I'm trying to figure out if it's possible to have a many-to-many relationship with self. Scenario is that users can have many managers and managers can manage many users.

First I tried this, which does not work (AttributeError: 'DeferredRelation' object has no attribute '_meta')

from peewee import SqliteDatabase
from peewee import CharField
from peewee import Model
from playhouse.fields import ManyToManyField
from playhouse.fields import DeferredRelation

db = SqliteDatabase(':memory:')

DeferredUser = DeferredRelation()

class User(Model):
name = CharField()

managed_users = ManyToManyField(DeferredUser)

class Meta:
database = db

DeferredUser.set_model(User)

User.create_table()

Anyway I can't see how that would work since it would try to create two "user_id" columns on the through model.

I can get it sort of working using an intermediary table and a property on the user. This doesn't get me the ability to "set" managed_users on a model instance like a ManyToMany field would.

class User(Model):
name = CharField()

class Meta:
database = db

@property
def managed_users(self):
return User.select() \
.join(ManagedUser, on=(ManagedUser.user_id == User.id)) \
.where(ManagedUser.manager_id == self.id)

class ManagedUser(Model):
manager = ForeignKeyField(User, related_name='manager_set')
user = ForeignKeyField(User, related_name='user_set')

class Meta:
database = db

So I guess my question... is it possible to do what I want using ManyToManyField? Or should I keep with the property and write my own setter?

Charles Leifer

unread,
May 5, 2017, 4:12:20 AM5/5/17
to peewe...@googlegroups.com
For an example of how to do this, check out the example "Twitter" app. It's very similar in that a user can follow many users, and a user can have many followers.


--
You received this message because you are subscribed to the Google Groups "peewee-orm" group.
To unsubscribe from this group and stop receiving emails from it, send an email to peewee-orm+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages