Marcus Renno Marcus Renno - 11 months ago 47
Python Question

Cannot get "_set" from model using "self" in foreign key

I'm trying to get the related objects using

in Django. I want to get all objects which are referring to the parent object.

My model:

class MessageBoard(models.Model):
title = models.CharField(max_length=40)
message = models.TextField()
person = models.ForeignKey(User)
date = models.DateTimeField()
parent = models.ForeignKey("self", default=None, null=True)

But when I try to get the set of an object I get an error.

>>> msg = MessageBoard.objects.get(pk=1)
>>> msgs = msg.parent_set.all()
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: 'MessageBoard' object has no attribute 'parent_set'

If I do

>>> MessageBoard.objects.filter(parent=1)

It returns the objects as I want. I need to use
(or another way which achieves the same result), because I want to use inside django templates.

Answer Source

The default back reference is not named by the field, but by the model. It should be messageboard_set.

Since the name is confusing, I advise to set the related_name on the ForeignKey.