I remodel my objects using ManyToMany relationship using "through" as it's guided here: 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
It looks ok, but I have 2 problems with it:
1) In admin management panel there's no easy connection with receipt = If I have to add a new component - I should go to components and make component connected to receipt - maybe it's the only solution - but it would be more intuitive in receipts
2) I can't print it using templates:
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 %}