2010-06-04 88 views
0

我“到”改造使用使用多对多关系,我的对象,因为它是在这里指导: 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 %} 

回答

1

你对.all所做的一切正是我的意思 - 你最初在2个地方使用.all()和view模板。

您的'错误'的原因很明显 - 组件是m2m字段到产品。这是你在代码中写的。这个组件是产品的集合,而不是中介模型ReceiptComponent

UPD:只要留下您的车型为是,并使用receiptcomponent_setReceipt

+0

正确! components = receipt.receiptcomponent_set.all() 解决了这个问题 Python&Django不会让我感到惊讶; D – 2010-06-05 06:52:50

0

1)您是否尝试过inlines? 2)删除模板中的.all,你不需要它。 也许你还需要 components = list(receipt.components.all())

0

1)看起来很完美! (提示为其他用户:直列=内联; d

2!)除去。所有会导致异常:

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 not ReceiptComponent。 unicode(这是产品的子)。为什么?

+0

奇怪。一个答案消失... – 2010-06-06 07:32:05

+0

否...; D答案上升; D – 2010-06-06 07:35:21