I have a model for a company. Then I have a base model for company posts. It contains common posts attributes. An attribute is the company that publishes the posts. It refers to the Company model with a ForeignKey. Finally I have a child model (based on the CompanyPost base model) for posts of type A:
class Company(models.Model):
name = models.CharField(...)
...
class CompanyPost(models.Model):
company = models.ForeignKey(Company,...)
...
class PostA(CompanyPost):
name = ...
In a template I want to loop over posts of type A published by a specific company.
I tried these variants:
1)
{% for postA in company.companyposts_set.all.postA_set.all %}
...
2)
{% for companyposts in company.companypost_set.all %}
{% for postA in companyposts.postA_set.all %}
...
{% endfor %}{% endfor %}
I tried other sub-variants of the above. None seems to work.
I know that I can easily prepare the set in the view, like:
postsA = PostA.objects.filter(company__pk=pk)
And pass postsA to the template context, but I'm wondering whether there is a way to loop over related models' children in the template.
(note: looping over companyposts works. But I get of course all types of posts, like postB etc.:
{% for post in company.companypost_set.all %}
That is why I tried variant 2) above to loop again over the results.)
Thank you in advance.
UPDATE: Thank you all for your answers. I understand that, by choosing model inheritance, I chose a convoluted solution. In the present post I'm asking whether displaying related model's children in a template is possible. In order not to confuse questions, in this question I explain why I used concrete model inheritance and ask what would be a better solution.