我「到」改造使用使用多對多關係,我的對象,因爲它是在這裏指導: link textDjango的複雜模型和模板
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 %}
正確! components = receipt.receiptcomponent_set.all() 解決了這個問題 Python&Django不會讓我感到驚訝; D – 2010-06-05 06:52:50