I am learning django. I have a simple model named customer. Here is my model:
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
here is my view of customer:
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)
Here is my 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 %}
Now I have to generate table row which will contain year,customer and product througth customer per year. So that How to fetch for every row that contains year, year based customer product data.
More simple, Year has many customers and customer has one product thought year.
How to generate this. Please help me.