Loop over related model's children in Django template

自作多情 提交于 2019-12-25 01:37:59

问题


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.


回答1:


If you don't want to define it in the views, you could define it as a property of Company objects.

@property
def post_a_set(self):
    return PostA.objects.filter(company__pk=self.pk)

I'm pretty sure it's the model inheritance that is causing the problems, and dimly remember seeing something like his documented. I'd echo, do you really need concrete model inheritance here? Other approaches are wider CompanyPost objects with a post_type choices field and other fields null or blank if inappropriate; or a post_type field and the data that applies only to that type stored as a JSON string or (if you are using Postgresql) a JSONField.



来源:https://stackoverflow.com/questions/59387158/loop-over-related-models-children-in-django-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!