S
S
serik2018-04-30 17:52:13
Django
serik, 2018-04-30 17:52:13

How to display records from a table related by ForeignKey?

There is a company table, each entry is a separate page

class Company(models.Model):
    user = models.ForeignKey(User, verbose_name=u"Директор", blank=True, null=True, on_delete=models.CASCADE)
    full_name = models.CharField("Полное наименование компании", default='»', max_length = 180)
    email = models.CharField("Электронная почта", default='', max_length = 180)
    background = models.ImageField("Фон", upload_to="annex/img/%Y/%m/%d", default='')

How to display the data of the second linked table?
class Work(models.Model):
    associate = models.ForeignKey(Company,blank=True,null=True,default=None, verbose_name=u'Компания', on_delete=models.CASCADE)
    name = models.CharField("Наименование", default='', max_length = 180)
    unit = models.CharField("Ед. изм", default='', max_length = 30)
    price = models.CharField("Цена за ед.", default='', max_length = 20)

Company records generated by new links
path('', ListView.as_view(queryset=Company.objects.all().order_by("name"),template_name="annex/company.html")),
url(r'(?P<pk>\d+)$', DetailView.as_view(model=Company,template_name="annex/full-company.html")),

I can’t figure out how to display the corresponding record of the Work table on the page with the company record

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Astrohas, 2018-04-30
@black_xe

object.work_set is a queryset of work class objects. iterate over it
like this:

{% for work in object.work_set.all %}
{# здесь делаете все что хотите #}
{%endfor%}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question