Skip to content
Advertisement

Accessing Parent Model from child element of ManyToManyField (Django)

I am having a models.py as follows

JavaScript

So let’s say i have a comment Object Instance which’s id is 2 and raw content

How to get parent post_id which contains this comment??

Advertisement

Answer

Use related_name. Small change adding: related_name='posts': think of it like “if we start from the opposite side, what would be the name to use” (it’s always plural).

JavaScript

Now you can do:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement