python - Django:使用子外键获取父数据

标签 python django

我在使用子项获取父项数据时遇到问题。

模型.py

class Company_Data(models.Model):
    company_name = models.CharField(max_length=254)
    company_address =  models.CharField(max_length=254)
    company_tel_no =  models.CharField(max_length=254)
    company_fax_no = models.CharField(max_length=254)


class Requirements(models.Model):
    req_service         = models.CharField(null=False, max_length=254)
    req_coverdate_from  = models.DateField()
    req_coverdate_to    = models.DateField()
    req_duedates        = models.DateField()
    company             = models.ForeignKey(Company_Data, on_delete=models.CASCADE)

View .py

def business_setup(request):

    req = Requirements.objects.filter(req_service = 'Business Setup')

    context = {
        'req' : req ,
    }
    return render(request, 'admin_template/content/admin_businesssetup_req.html', context)

模板 HTML

{% for requirements in req %}
<table>
                    <tbody>

                      <tr>
                      <th style="width:50%">Company Name</th>
                      <td>{{ requirements.company_id.company_name }}</td>
                      </tr>

                      <tr>
                      <th> Covered Date From </th>
                      <td>{{ requirements.req_coverdate_from }}</td>
                      </tr>
                      <tr>
                      <th> Covered Date To </th>
                      <td>{{ requirements.req_coverdate_to }}</td>
                      </tr>
                      <tr>
                      <th> Due Date </th>
                      <td>{{ requirements.req_duedates }}</td>
                      </tr>
                    </tbody>
                  </table>

{% endfor %} 

我尝试的是requirements.company_id.company_name来显示相关的公司名称,但没有成功。我发现查询父 Company_Date 以显示子 Requirements。但我想过滤 Requirements 表并显示它的父表,因此这些不适用于我。

谢谢你..

最佳答案

You just have to write "company" instead of "company_id" in your template

<td>{{ requirements.company.company_name }}</td>

关于python - Django:使用子外键获取父数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58785462/

相关文章:

python - 如何让winsound只要按下激活播放声音的键就播放声音?

django - 为什么 Django 中没有 "ListField"?

python - 如何将 angular 4 与 Django 集成

python - 在网络上显示 pyqtgraph 和 pyqt 小部件

javascript - Django元素中第三方静态文件推荐的目录布局是怎样的?

python - 在不破坏导入的情况下将独立的 django 脚本放在哪里?

python - 在 SQLAlchemy 中按自引用子集合的长度对对象进行排序

python - 浮点取模问题

python /网络 : What's the best way to run Python on a web server?

python - 由 <function check_errors.<locals>.wrapper at 0x03A69780> 启动的线程中出现未处理的异常