0
我正在学习django。我有一个名为customer的简单模型。这里是我的模型:如何通过使用数据获取有很多通过django?
class Year(models.Model):
year = models.CharField(max_length=255)
created_at = models.DateTimeField(auto_now=False, auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True, auto_now_add=False)
def __unicode__(self):
return self.year
def __str__(self):
return self.year
class Customer(models.Model):
name = models.CharField(max_length=255)
created_at = models.DateTimeField(auto_now=False, auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True, auto_now_add=False)
def __unicode__(self):
return self.name
def __str__(self):
return self.name
class Product(models.Model):
customer_name = models.ForeignKey(Customer, on_delete=models.CASCADE)
quantity = models.CharField(max_length=255)
year = models.ForeignKey(Year, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now=False, auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True, auto_now_add=False)
def __unicode__(self):
return self.score
def __str__(self):
return self.score
这里是我的客户的看法:
from django.shortcuts import render, get_object_or_404, redirect
from .models import Customer, Product, Year
# Create your views here.
def home(request):
customer = Customer.objects.all
product = Product.objects.all
year = Year.objects.all().prefetch_related('product_set')
context = {'customers': customer,
'years': year,
'products': product
}
return render(request, 'customer.html', context)
这里是我的customer.html
{% extends 'base.html' %}
{% block customer %}
<div class="container">
<h2>Players Table</h2>
<p>Customer with Product</p>
<table class="table">
<thead>
<tr>
<th>Year/Product</th>
{% for customer in cutomers %}
<th>{{ customer.name }}</th>
{% endfor %}
</tr>
</thead>
<tbody>
{# <tr>#}
{# <th>2011</th>#}
{# <th>633</th>#}
{# <th>424</th>#}
{# </tr>#}
{# <tr>#}
{# <th>2012</th>#}
{# <th>353</th>#}
{# <th>746</th>#}
{# </tr>#}
</tbody>
</table>
</div>
{% endblock customer %}
现在我必须产生表行其中将包含一年,客户和产品每年通过客户。 因此,如何获取包含年,年客户产品数据的每一行。
更简单, 年有很多客户和客户有一个产品思想的一年。
如何生成这个。请帮帮我。
感谢您的回复。但是我必须生成一个2D表格,其中一列只显示一年(不重复),其他列包含产品数据。 –
你能告诉我输出欲望吗? – Wilfried
输出将返回包含三列的表格: 1.第一列<<全年(不重复) 2.第二列<<第一顾客的产品数据 3.第三列<<第二顾客的产品数据 您可以看到customer.html –