capcom-r
capcom-r

Reputation: 105

Django ManyToMany Creating Duplicate Relationship for Self Referential Attribute

I've got a model that looks something like this:

class Session(models.Model):
    sub_sessions = models.ManyToManyField("self")

Now when I do something like:

session_1 = Session.objecte.get(id=1)
session_2 = Session.objects.get(id=2)
session_1.sub_sessions.add(session_2)

What happens is that a relationship is created such that session_2 is in session_1's sub_sessions field, but session_1 is also in session_2's sub_sessions field.

I imagine this makes sense at some level being a ManyToManyField relationship, but it's really not what I want. I only want session_2 to be in session_1's sub_sessions field, but not the other way around.

I suppose I can instead create a ForeignKey relationship, but it'll just break a few of my current coding implementations and I'd really love to have some sort of a way to make this work.

Thanks!

Upvotes: 0

Views: 45

Answers (1)

BottleZero
BottleZero

Reputation: 983

Is the symmetrical property what you are looking for?

class Session(models.Model):
    sub_sessions = models.ManyToManyField("self", symmetrical=False)

Django docs

Upvotes: 2

Related Questions