我正在努力寻找有关如何在一个表单上显示数据或从多个模型中引用数据的良好信息。现在我用servicereports模型生成一个listview。在该列表视图中,我选择了几列来显示(Customer,Date,Originator)。客户列实际上填充了对另一个模型(客户模型)的主键引用。如何使用该pk并使用它来引用其他模型的实际客户名称?
models.py
class Companies(models.Model):
company_name = models.CharField(db_column='Company Name', max_length=50)
billing_address = models.CharField(db_column='Billing Address', max_length=255, blank=True, null=True)
company_id = models.AutoField(db_column='Company ID', primary_key=True)
class ServiceRecords(models.Model):
sr_id = models.CharField(db_column='SR ID', primary_key=True, max_length=50)
company_id = models.IntegerField(db_column='Company ID', blank=True, null=True)
...
views.py
class ServiceReportIndex(LoginRequiredMixin, ListView):
context_object_name = 'all_servicereports'
login_url = 'login'
template_name = 'servicereport/servicereport_index.html'
queryset = ServiceRecords.objects.all()
def get_context_data(self, **kwargs):
context = super(ServiceReportIndex, self).get_context_data(**kwargs)
context['companies'] = TblCompanies.objects.all()
return context
因此,在这种情况下,我想在使用ServiceRecords模型生成的列表中使用customers.company_name。
template.html
<p><a href="{% url 'servicereport:servicereport_detail' servicereport.sr_id %}">{{ customers.company_name }}</a></p>