Reputation: 53
I've created an invoice system where I can assign an item to a user and they can view a list of items assigned. The problem is, I need to show the price of the item as well. I can not figure out how to even begin querying for that attribute. I feel like everything is solid until I get to views. Maybe the code can articulate my issue better than I can.
## models.py
class Invoice(models.Model):
date_of_service = models.DateTimeField(default=datetime.now(),blank=True)
agency_to_bill = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True)
service_compelted = models.ForeignKey('Service', blank=True)
paid = models.CharField(max_length="50", choices=invoicePaid, default='False')
def __unicode__(self):
return unicode(self.agency_to_bill)
class Service(models.Model):
name_of_service = models.CharField(max_length="50")
cost = models.CharField(max_length="50")
def __unicode__(self):
return unicode(self.name_of_service)
##views.py
def invoicelist(request):
span = Bill_Period.objects.all()
return render_to_response('invoice-list.html', {'span': span})
def InvoiceDetail(request, month, year):
current_user = request.user.id
invoice_detail = invoice.objects.filter(date_of_service__year=year, date_of_service__month=month, agency_to_bill=current_user)
context = {'invoice_detail': invoice_detail}
return render_to_response('invoice-detail.html', {'invoice_detail': invoice_detail,
'current_user': current_user})
##invoice-detail.html
{% for p in invoice_detail %}
{{ p.therapy_compelted }} {{ <!--PRICE HERE--> }}
{% endfor %}
Upvotes: 0
Views: 250
Reputation: 17124
You can access foreign key elements attributes directly in template without having a specific query in your view. As long as you have your main objects in your context (invoices in your case), you can access elements related via foreign key as if it was direct attribute.
Not sure about the names of your variables, you're talking about price, but it's not in your model, then in your template you have therapy_complete, but in your model you have service_completed.
But in any case accessing foreign key in template is very easy. Like this:
{{ p.service_completed.cost }}
Upvotes: 2