我創建了一個發票系統,我可以將一個項目分配給用戶,他們可以查看已分配項目的列表。問題是,我需要顯示該項目的價格。我無法弄清如何開始查詢該屬性。我覺得一切都很穩固,直到我看到。也許代碼可以比我更好地表達我的問題。查詢ForeignKey的屬性並填充
## 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 %}
您可能需要使用.select_related(「foreignkeyX」,「foreignkeyY」)上的查詢集創建連接和節省一些對噸,額外的SQL查詢:-) – ACimander