我使用“to”使用ManyToMany关系重新构建我的对象,因为它在这里引导: link text
class Receipt(models.Model):
name = models.CharField(max_length=128)
(...)
components = models.ManyToManyField(Product, through='ReceiptComponent')
class Admin:
pass
def __unicode__(self):
return self.name
def url(self):
return self.id
class ReceiptComponent(models.Model):
product = models.ForeignKey(Product)
receipt = models.ForeignKey(Receipt)
quantity = models.FloatField(max_length=9)
unit = models.ForeignKey(Unit)
class Admin:
pass
def __unicode__(self):
return unicode(self.quantity!=0 and self.quantity or '') + ' ' + unicode(self.unit) + ' ' + self.product.genitive
看起来不错,但我遇到了2个问题:
1)在管理员管理面板中,没有与收据的简单连接=如果我必须添加一个新组件 - 我应该去组件并使组件连接到收据 - 也许这是唯一的解决方案 - 但它会更直观收据
2)我无法使用模板打印它:
views.py:
(...)
def detail(request, receipt_id):
receipt = get_object_or_404(Receipt, pk=receipt_id)
components = receipt.components.all()
return render_to_response('receipt.html',{'receipt' : receipt, 'components' : components,}
(...)
receipt.html:
<h1>{{ receipt.name }}</h1>
{% for component in components.all %}
<div class='component'>{{ component }}</div>
{% endfor %}
答案 0 :(得分:1)
你做了什么.all正是我的意思 - 你最初在2个地方,.all()在视图和.all在模板中。
“错误”的原因非常明显 - 组件是产品的m2m字段。这是您在代码中写的内容。此组件是产品集,而不是中间模型 ReceiptComponent 。
UPD :只需保留模型,然后使用receiptcomponent_set
Receipt
答案 1 :(得分:0)
1)您是否尝试过inlines?
2)在模板中删除.all,您不需要它。 可能你也需要 components = list(receipt.components.all())
答案 2 :(得分:0)
1)看起来很完美! (提示其他用户:内联!=内联; D
2)删除.all会导致异常:
Caught an exception while rendering: 'ManyRelatedManager' object is not iterable
但我理解为了获得高质量的代码,我应该将其从模板转移到代码:
views.py:
def detail(request, receipt_id):
receipt = get_object_or_404(Receipt, pk=receipt_id)
components = receipt.components.all()
additionals = receipt.additionals.all()
return render_to_response('drinkbook/receipts/receipt.html',{'receipt' : receipt, 'components' : components, 'additionals' : additionals, })
模板:
h1>{{ receipt.name }}</h1>
{% for component in components %}
<div class='component'>{{ component }}</div>
{% endfor %}
{% if receipt.additionals %}Ponadto:
{% for additional in additionals %}
<div class='additional'>{{ additional }}</div>
{% endfor %}
{% endif %}
<p>{{ receipt.desc|safe }}</p>
确定。它现在有效,但组件的结果是Product。 unicode 而不是ReceiptComponent。 unicode (它是Product的子级)。为什么呢?