Paul Noon
Paul Noon

Reputation: 686

Retrieve all reverse foreign keys in Django

Given a specific Placerating object, which points to a ThePlace object, how to retrieve all ThePlace objects which points to this ThePlace object.

Please note that ThePlace has a recursive relationship to itself.

Model:

class ThePlace(models.Model):
    author = models.ForeignKey('auth.User')
    upperlevelplace = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, related_name='upperlevelplaces')

class Placerating(models.Model):
    theplace = models.ForeignKey('ThePlace', on_delete=models.CASCADE, null=True, related_name='placeratings')

I have tried this View:

placerating = Placerating.objects.get(pk=15)

qs = placerating.theplace.upperlevelplaces()
print(qs)

But I get the following error:

qs = placerating.theplace.upperlevelplaces() File "C:\aa\aa\env\lib\site-packages\django\db\models\fields\related_descriptors.py", line 505, in __call__manager = getattr(self.model, kwargs.pop('manager')) KeyError: u'manager'

Upvotes: 0

Views: 410

Answers (1)

Sayse
Sayse

Reputation: 43300

You're trying to use the related key as a callable, it returns a model manager so you can use all on that

qs = placerating.theplace.upperlevelplaces.all()

Upvotes: 2

Related Questions