0

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.

HM Tanbir
  • 990
  • 12
  • 30

1 Answers1

1

You don't need product or year in your context. You can use relation between your models to get this information:

views.py

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
    context = {'customers': customer}
    return render(request, 'customer.html', context)

Now in your template you can get :

All product of a customer, with year by product

{% for customer in customers %}
   Customer : {{ customer }}<br>
   {% for product in customer.product_set.all %}
       Product : {{ product }} / Year :{{ product.year }}<br>
   {% endfor %}
{% endfor %}

But I don't like put too much logic in template. I advise you to create the data of your table in your view, even better in your model. And then generate your html table with this data.

Summary of the function you will need: You can replace all() by a filter()

products = customer.product_set.all() # give you all product of a customer

UPDATE AFTER COMMENTS:

Views.py

from django.shortcuts import render, get_object_or_404, redirect
from .models import Customer, Product, Year

# Create your views here.
def home(request):
    customers = Customer.objects.all()
    years = Year.objects.all().values_list('year', flat=True).asc() # List of year name 
    rows = []
    for year in years:
        row = [year] + [None] * len(customers) # Row with year in first column, and the rest init with same size of customers list
        for idx, customer in enumerate(customers):
            quantities = customer.product_set.filter(year__year=year).valu e_list('quantity', flat=True) # filter product by year. That can return multiple product !!! 
            row[idx + 1] = ' ,'.join(quantities) # create a string of quantities
        rows.append(row) # Add new row in our rows list
    context = {'customers': customer,
               'rows': rows}
    return render(request, 'customer.html', context)

template:

{% 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 customers %}
              <th>{{ customer.name }}</th>
          {% endfor %}
      </tr>
    </thead>
      <tbody>
        {% for row in rows %}
            <tr>
                {% for cell in row %}
                    <th>cell</th>
                {% endfor %}
            </tr>
        {% endfor %}
      </tbody>
  </table>
</div>

I think that can help you to understand how to resolve your problem. I don't test this code, so maybe there is error. This is not perfect !

Wilfried
  • 1,623
  • 1
  • 12
  • 19
  • thanks for your reply. But I have to generate a 2D table, in where one column show only year(does not repeat), other columns contains the product data. – HM Tanbir Mar 24 '17 at 14:40
  • Output will return a table which contains three column: 1. first column << All Year (no repeating) 2. second column << product data of first customer 3. third column << product data of second customer You can see the table of customer.html – HM Tanbir Mar 24 '17 at 17:31
  • Thanks for reply. It works but it has an error. first column returns << 2010, Second column return << ]> Third column << ]> We need only value of queryset , i.e; 2nd column << 12, 3rd column << 14 – HM Tanbir Mar 25 '17 at 02:56
  • Reply updated. Have you tried anything to solve your problem? Because you ask for the solution every time. It's a help site. You do not have to do your job for you :) It will be my last update;) Glad to help you. – Wilfried Mar 25 '17 at 09:15
  • Thanks Wilfried. You are great man. I am learning python and django. I am not expert in django. If this problem is occurred in Ruby on rails, I will solve it 10 minutes because I am profession in Ruby on rails, but in django, I am beginner, in learning phase. You bored my question , I am sorry for that. If you did not help me, I could not learn new things in django. So, I again say you thank you very much. – HM Tanbir Mar 25 '17 at 15:46