简体   繁体   中英

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'

您正在尝试使用相关键作为可调用键,它会返回模型管理器,因此您可以在其中使用all

qs = placerating.theplace.upperlevelplaces.all()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM