django:通过 view.py 中的向后关系检索对象,而不是模板
刚开始用 python 编程,我遇到了以下问题。我有一个显示供应商详细信息的模板,每个供应商都有员工,在模板页面上,我想显示员工的姓名。我知道如何在模板中执行此操作,但是如何在视图中执行此操作?
模型:
class Supplier(models.Model):
co_name = models.CharField(max_length=100)
co_city = models.CharField(max_length=100)
co_state = models.CharField(max_length=2)
class Supplieremployees(models.Model):
supplier = models.ForeignKey(supplier)
expe_fname = models.CharField(max_length=50)
视图:
def supplier_detail(request, supplier_id):
s = get_object_or_404(Supplier, pk=supplier_id)
**test = s.supplieremployees_set.all()**
return render_to_response('suppliersdb/supplier_detail.html', {'supplier': s})
模板:
...i dont want to use this way, how do i translate this into the view?
{% for supplieremployees in supplier.supplieremployees_set.all %}
<li>IT Focal: {{ supplieremployees.expe_fname }}</li>
{% endfor %}
**TEST: {{ test.expe_fname }}**
{{ test.expe_fname }} 没有显示任何内容
Just starting out to program in python and I'm having the following issue. I have a template that shows details on a supplier, each supplier has employees and on the template page, I want to show the names of the employees. I know how to do it in the template, but how do you do that in the view?
MODELS:
class Supplier(models.Model):
co_name = models.CharField(max_length=100)
co_city = models.CharField(max_length=100)
co_state = models.CharField(max_length=2)
class Supplieremployees(models.Model):
supplier = models.ForeignKey(supplier)
expe_fname = models.CharField(max_length=50)
VIEWS:
def supplier_detail(request, supplier_id):
s = get_object_or_404(Supplier, pk=supplier_id)
**test = s.supplieremployees_set.all()**
return render_to_response('suppliersdb/supplier_detail.html', {'supplier': s})
TEMPLATE:
...i dont want to use this way, how do i translate this into the view?
{% for supplieremployees in supplier.supplieremployees_set.all %}
<li>IT Focal: {{ supplieremployees.expe_fname }}</li>
{% endfor %}
**TEST: {{ test.expe_fname }}**
nothing shows up for {{ test.expe_fname }}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
来自文档
from the docs
Supplier
对象将具有可访问反向关系的supplieremployees_set
属性:您还可以向
ForeignKey< 提供
lated_name
参数/code> 并使用它:A
Supplier
object will have asupplieremployees_set
property that can access the reverse relation:You can also supply a
related_name
argument to theForeignKey
and use that: