views:

17

answers:

1

Following regular manytomany queryset logic gives me errors. I guess since its related to self, I might need to do some extra magic, but i can't figure out what magic.

model:

class Entry(models.Model):
    title   =   models.CharField(max_length=100, verbose_name='title')
    related     =   models.ManyToManyField('self', related_name='related_entries', blank=True)

queryset:

entry = Entry.objects.get(pk=1)
related = entry.related_entries.all()

error: 'Entry' object has no attribute 'related_entries'

+2  A: 

Look at the documentation for the symmetrical argument to ManyToManyField:

When Django processes this model, it identifies that it has a ManyToManyField on itself, and as a result, it doesn't add a person_set attribute to the Person class. Instead, the ManyToManyField is assumed to be symmetrical -- that is, if I am your friend, then you are my friend.

If you do not want symmetry in many-to-many relationships with self, set symmetrical to False. This will force Django to add the descriptor for the reverse relationship, allowing ManyToManyField relationships to be non-symmetrical.

So, in order to use the related_name, set symmetrical=False.

Daniel Roseman
Kasper
Kasper: in that case, you want them to be symmetric: just delete the `related_name` instead, and use `entry.related.all()`
Piet Delport
Piet, thanks! that did the trick
Kasper