Note that there are some explanatory texts on larger screens.

plurals
  1. POdjango complex model and template
    text
    copied!<p>I remodel my objects using ManyToMany relationship using "through" as it's guided here: <a href="http://docs.djangoproject.com/en/1.0/topics/db/models/#intermediary-manytomany" rel="nofollow noreferrer">link text</a></p> <pre><code>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 </code></pre> <p>It looks ok, but I have 2 problems with it:</p> <p>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</p> <p>2) I can't print it using templates:</p> <p>views.py:</p> <pre><code>(...) 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,} (...) </code></pre> <p>receipt.html:</p> <pre><code>&lt;h1&gt;{{ receipt.name }}&lt;/h1&gt; {% for component in components.all %} &lt;div class='component'&gt;{{ component }}&lt;/div&gt; {% endfor %} </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload