ManyToManyField('self') not using related_name

17 views
Skip to first unread message

Farhan Khan

unread,
Jul 19, 2016, 2:52:16 PM7/19/16
to Django users
I am using a ManyToManyField whose target is a 'self' reference, but it does not create a related_name "reverse" field.

Here is my model:

class SecurityGroup(models.Model):
    name
= models.CharField(max_length=100)
    description
= models.TextField()
    subgroups
= models.ManyToManyField('self', related_name='origin')

   
def __str__(self):

       
return self.name


And here is the problem:


>>> x = SecurityGroup(name='name', description='description')
>>> x.save()
>>> x.origin()
Traceback (most recent call last):
 
File "<console>", line 1, in <module>
AttributeError: 'SecurityGroup' object has no attribute 'origin'


There also no x.securitygroup_set. Is this a bug?



Farhan Khan

unread,
Jul 19, 2016, 2:54:59 PM7/19/16
to Django users
The solution was that I needed to set symmetrical=False, per the documentation here: https://docs.djangoproject.com/en/1.9/ref/models/fields/#django.db.models.ManyToManyField.symmetrical
Reply all
Reply to author
Forward
0 new messages