Home>

I'm new to django.
django I want to get a child table in a loop on a parent table.

● models.py
class Company (models.Model):
    name = models.CharField (verbose_name = u'company name', max_length = 50, blank = True, null = True)
    address = models.CharField (verbose_name = u'address', max_length = 100, blank = True, null = True)
    email = models.CharField (verbose_name = u'email address', max_length = 50, blank = True, null = True)
    tel = models.CharField (verbose_name = u'phone number', max_length = 50, blank = True, null = True)
    created_date = models.DateTimeField (auto_now_add = True)
    updated_date = models.DateTimeField (auto_now = True)
class Service (models.Model):
    company = models.ForeignKey (Company, on_delete = models.CASCADE)
    service_detail = models.TextField (verbose_name = u'service content', blank = True, null = True)
    created_date = models.DateTimeField (auto_now_add = True)
    updated_date = models.DateTimeField (auto_now = True)


In html
-Parent table data
--------- Child table data
--------- Child table data
-Parent table data
--------- Child table data
--------- Child table data
--------- Child table data

How can I display it?
I don't know if it's set in template or views.py.

Supplementary information (FW/tool version, etc.)

django = 2.2
pyhton = 3.8
mysql = 14.14 Distrib 5.7.31

  • Answer # 1

    company = models.ForeignKey (Company, related_name = "se_company", on_delete = models.CASCADE)

    related_nameIs added and back-referenced.

    {% for company in object_list%}
      {% for s in company.se_company.all%}
        {{s}}
      {% endfor%}
    {% endfor%}

  • Answer # 2

    I think there are several methods, but I think that it can be obtained by doing the following in HTML.

    {% for company in object_list%}
    (% for s in company.service_set.all%}
    {{s}}
    {% endfor%}
    {% endfor%}

    References: Get aggregated values ​​for Django one-to-many (one2many) related child tables – igreks development diary