How to merge two Querysets and create new queryset in django - django

I have two models for two parts of AC, that is IndoorInventory for the indoor unit which shows all indoor unit information, and OutdoorInventory for showing outdoor unit information.
class IndoorInventory(models.Model):
client = models.ForeignKey(Client, on_delete=models.CASCADE)
product = models.CharField(max_length=50)
indoor_brand = models.CharField(max_length=100, null=True, blank=True)
indoor_model_no = models.CharField(max_length=100, null=True, blank=True)
indoor_sr_no = models.CharField(max_length=100, null=True, blank=True)
outdoor_model_no = models.CharField(max_length=100, null=True, blank=True)
class OutdoorInventory(models.Model):
client = models.ForeignKey(Client, on_delete=models.CASCADE)
product = models.CharField(max_length=50)
outdoor_brand = models.CharField(max_length=100, null=True, blank=True)
outdoor_model_no= models.CharField(max_length=100, null=True, blank=True)
outdoor_sr_no = models.CharField(max_length=100, null=True, blank=True)
indoor_model_no= models.CharField(max_length=100, null=True, blank=True)
I am passing a queryset of IndoorInventory to my Django template and fetching all the data there. Below is my VIEW
def clientInventory(request):
context = {}
client_id = request.GET.get('client_id')
id_inven = IndoorInventory.objects.filter(client=client_id)
od_inven = OutdoorInventory.objects.filter(client=client_id)
context['id_inven'] = id_inven
return render(request, 'client-inventory.html', context)
My Template Below
<table id="client-invent-admin" class="table table-striped table-bordered display nowrap">
<thead>
<tr>
<th class="filterhead">ID</th>
<th class="filterhead">Brand</th>
<th class="filterhead">Product/Type</th>
<th class="filterhead">ID Model No</th>
<th class="filterhead">ID SR No</th>
<th class="filterhead">OD Model No</th>
<th class="filterhead">Actions</th>
</tr>
<tr>
<th>ID</th>
<th>Brand</th>
<th>Product/Type</th>
<th>ID Model No</th>
<th>ID SR No</th>
<th>OD Model No</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{% for invent in id_inven %}
{% if invent.indoor_model_no == '' %}
<tr class="bg-danger">
<td>{{ invent.id }}</td>
<td>{{ invent.indoor_brand }}</td>
<td>{{ invent.product }}</td>
<td>{{ invent.indoor_model_no }}</td>
<td>{{ invent.indoor_sr_no }}</td>
<td>{{ invent.outdoor_model_no }}</td>
<td>
<div class="dropdown icon-dropdown">
<a class="btn-icon dropdown-toggle" data-toggle="dropdown" href="#">
<i class="zmdi zmdi-more"></i>
</a>
<div class="dropdown-menu dropdown-menu-right">
<a class="dropdown-item" href="#"><i class="feather icon-eye"></i> View</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="#"><i class="feather icon-edit"></i> Edit</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item"
href="/delClient-invent/?invent_id={{invent.id}}&client_id={{client_id}}">
<i class="feather icon-trash"></i> Delete
</a>
</div>
</div>
</td>
</tr>
{% else %}
<tr>
<td>{{ invent.id }}</td>
<td>{{ invent.indoor_brand }}</td>
<td>{{ invent.product }}</td>
<td>{{ invent.indoor_model_no }}</td>
<td>{{ invent.indoor_sr_no }}</td>
<td>{{ invent.outdoor_model_no }}</td>
<td>
<div class="dropdown icon-dropdown">
<a class="btn-icon dropdown-toggle" data-toggle="dropdown" href="#">
<i class="zmdi zmdi-more"></i>
</a>
<div class="dropdown-menu dropdown-menu-right">
<a class="dropdown-item" href="#"><i class="feather icon-eye"></i> View</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="#"><i class="feather icon-edit"></i> Edit</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item"
href="/delClient-invent/?invent_id={{invent.id}}&client_id={{client_id}}">
<i class="feather icon-trash"></i> Delete
</a>
</div>
</div>
</td>
</tr>
{% endif %}
{% endfor %}
</tbody>
<tfoot>
<tr>
<th>ID</th>
<th>Brand</th>
<th>Product/Type</th>
<th>ID Model No</th>
<th>ID SR No</th>
<th>OD Model No</th>
<th>Actions</th>
</tr>
</tfoot>
</table>
See table frontend
Now I want to get the outdoor_sr_no from OutdoorInventory models and pass it to the IndoorInventory Queryset so that the outdoor_sr_no value also get fetched on the table next to (OD model no) column in the table

You can use the chain method which concatenates the querysets
from itertools import chain
result_list = list(chain(q1, q2, q*))
The chain method returns a chained object, so you transform it into a list and then you can get the information.
You can also use the union method (Django Union Method)
qs1.union(qs2)
See more information in How can I combine two or more querysets in a Django view?

In your clientInventory method, you could add od_inven to your context dict.
context['id_inven'] = id_inven
context['od_inven'] = od_inven
Then you could use that in your template in the same way you are currently using id_inven. Something like:
...
<body>
{% for foo in od_inven %}
...
<td>{{ foo.id }}</td>
...

Related

How to display items on html table from django model base on its category

I have items in a Stock model and each item has a category that it belongs to. I want it to iterate through the Stock model, find the distinct category, display the items that relate to that category, and display the category name as a caption above the related items on the table.
model.py
class Stock(models.Model):
user = models.ForeignKey(User, on_delete = models.SET_NULL, null = True)
part_No = models.CharField(max_length=100, null=True)
item_name = models.CharField(max_length=100, null=True)
category = models.CharField(max_length=100, null=True)
unit = models.CharField(max_length=50, null=True)
balance_bd = models.IntegerField(default='0', null = True)
received = models.IntegerField(default='0', null = True)
issued = models.IntegerField(default='0', null=True)
unit_price = models.DecimalField(max_digits=20, decimal_places=2, null=True)
obsolete = models.BooleanField(default=False, null=True)
views.py
def stock(request):
stocks = Stock.objects.all()
context = {
'stocks':stocks,
}
return render(request, 'base/stock.html', context)
html template
<!-- DATA TABLE-->
<div class="table-responsive m-b-40">
<table class="table table-borderless table-data3">
<thead>
<tr class="bg-primary">
<th>NO</th>
<th>PART NO</th>
<th>DESCRIPTION</th>
<th>CATEGORY</th>
<th>UNIT</th>
<th>BALANCE B/D</th>
<th>RECEIVED</th>
<th>TOTAL BAL</th>
<th>ISSUED</th>
<th>TALLY CARD BAL</th>
<th>UNIT PRICE</th>
<th>TOTAL PRICE</th>
<th>ACTION</th>
</tr>
</thead>
<tbody>
{% for stock in stocks %}
{% if stock.obsolete %}
<tr>
<td>{{forloop.counter}}</td>
<td class="text-success"><i>{{stock.part_No}}</i></td>
<td class="text-success"><i>{{stock.item_name}}(obsolete)</i></td>
<td class="text-success"><i>{{stock.category}}</i></td>
<td class="text-success"><i>{{stock.unit}}</i></td>
<td class="text-success"><i>{{stock.balance_bd}}</i></td>
<td class="text-success"><i>{{stock.received}}</i></td>
<td class="text-success"><i>{{stock.total_bal}}</i></td>
<td class="text-success"><i>{{stock.issued}}</i></td>
<td class="text-success"><i>{{stock.tally_card_bal}}</i></td>
<td class="text-success"><i>{{stock.unit_price}}</i></td>
<td class="text-success"><i>¢{{stock.total_price}}</i></td>
<td>
<div class="table-data-feature">
<a href="{% url 'update-item' stock.id %}"> <button class="item" data-toggle="tooltip" data-placement="top" title="Update">
<i class="zmdi zmdi-edit"></i>
</button></a>
<button class="item" data-toggle="tooltip" data-placement="top" title="Delete">
<i class="zmdi zmdi-delete"></i>
</button>
</div>
</td>
</tr>
{% else %}
<tr>
<td>{{forloop.counter}}</td>
<td>{{stock.part_No}}</td>
<td>{{stock.item_name}}</td>
<td>{{stock.category}}</td>
<td>{{stock.unit}}</td>
<td>{{stock.balance_bd}}</td>
<td>{{stock.received}}</td>
<td>{{stock.total_bal}}</td>
<td>{{stock.issued}}</td>
<td>{{stock.tally_card_bal}}</td>
<td>¢{{stock.unit_price}}</td>
<td>¢{{stock.total_price}}</td>
<td>
<div class="table-data-feature">
<a href="{% url 'update-item' stock.id %}"> <button class="item" data-toggle="tooltip" data-placement="top" title="update">
<i class="zmdi zmdi-edit"></i>
</button></a>
<button class="item" data-toggle="tooltip" data-placement="top" title="Delete">
<i class="zmdi zmdi-delete"></i>
</button>
</div>
</td>
</tr>
{% endif %}
{% empty %}
<p>No item in stock</p>
{% endfor %}
<tr>
<td></td>
<td></td>
<td></td>
<td colspan="8" style="font-weight: bold;">TOTAL PRICE</td>
<td class="text-success" style="font-weight: bold;">¢{{sumTotalPrice}}</td>
<td></td>
</tr>
</tbody>
</table>
</div>
<!-- END DATA TABLE-->
These is the results I have so far
my stock table
And I want it to look like this image
Django Provided regoup template tag you can easily understand from Django official documentation
Link is here

how can you display data from three related tables in django?

I'm new to django and I'm having trouble displaying related data from three related databases in a table. I hope you can help me.
Models.py
class recursos (models.Model):
gruporecurso= models.CharField (max_length=50, choices=TIPORECURSO, default=TIPODEFAULT)
descripcion = models.CharField(max_length=100)
estado_disponible =models.BooleanField(default= True)
inventario = models.CharField(max_length=40,blank= True, null=True)
observacion = models.TextField(blank= True, null=True)
def __str__(self):
return self.descripcion
class remito (models.Model):
fecha = models.DateField()
hora = models.TimeField()
responsable = models. ForeignKey(personas, null=True, blank= True, verbose_name='Responsable',on_delete=models.CASCADE)
area_pedido = models.CharField(max_length=20, verbose_name='Área del pedido')
operador = models.CharField(max_length=40, choices=OPERADOR,verbose_name='Entregado por')
lugardeuso = models.CharField(max_length=40,verbose_name='Lugar uso')
observacion = models.TextField(blank= True, null=True)
class detalle_remito (models.Model):
id_remito = models.ForeignKey(remito, null=True, blank=False, on_delete=models.CASCADE)
id_recurso = models.ForeignKey(recursos, null=True, blank=False, on_delete=models.CASCADE)
cantidad = models.IntegerField(default=1)
def __str__(self):
return f' {self.id_recurso.descripcion}'
Views.py
def home (request):
remitos= remito.objects.all()
recursolist= detalle_remito.objects.all()
page= request.GET.get('page',1)
try:
paginator = Paginator(remitos,5)
remitos=paginator.page(page)
except:
raise Http404
return render(request,"RemitoTicapp/home.html",{'entity': remitos ,'recursolist':recursolist,'paginator': paginator})
home.html
{% extends "RemitoTicapp/base.html" %}
{% load static %}
{% block content %}
<!-- Heading
<section class="page-section clearfix">
<div class="container">
</div>
</div>
</section>
-->
<!-- Message -->
<section class="page-section cta">
<div class="container mx-auto">
<div class="row">
<!--<div class="col-xl-9 mx-auto"> -->
<div class="cta-inner text-center rounded">
<h2 class="section-heading mb-2">
<span class="section-heading-upper">Sistema de Gestión de pedidos</span>
<span class="section-heading-lower"> Elementos cedidos</span>
</h2>
<!--<p class="mb-0"> -->
<table class="table table-striped" bg white>
<thead>
<tr>
<th scope="col">Fecha entrega</th>
<th scope="col">Responsable</th>
<th scope="col">Area Pedido</th>
<th scope="col">Lugar de uso</th>
<th scope="col">Recurso / cantidad</th>
<th scope="col">Operador</th>
<th scope="col">Observaciones</th>
</tr>
</thead>
<tbody>
{% for remito in entity %}
<tr>
<td scope="row">{{ remito.fecha }}</td>
<td>{{ remito.responsable }}</td>
<td>{{ remito.area_pedido }}</td>
<td>{{ remito.lugardeuso }}</td>
<td> {% for recurso in recursolis %}
{% if recurso.id_remito == remito.pk %}
<li>{{ recurso.id_recurso.descripcion }} {{recurso.cantidad}}</li>
{% endif %}
{% endfor %}
</td>
<td>{{ remito.operador }}</td>
<td>{{ remito.observacion }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<div>
{% include 'RemitoTicapp/paginator.html' %}
</div>
<!-- </p> -->
</div>
</div>
<!-- </div> -->
</div>
</section>
{% endblock%}
We should show the data of Remito with the resources of detalle_remito with the description of each one of them from the recursos table.
From already thank you very much
Django will make the reverse foreign key relation accessible with the related model's name followed by a _set-suffix, exposing an instance of RelatedManager.
{% for detalle_remito in remito.detalle_remito_set.all %}
{{ detalle_remito.id_recurso.descripcion }}
{% endfor %}
No need to gather addional data for that in your view.
Where you have {% for recurso in recursolis %}, you could instead write {% for recurso in remito.detalle_remito_set.all %} and remove the if statement - it will loop through the detalle_remito objects that are connected to the recurso object

Update data in database based on order id in Django

I am new in Django.
I want to update the value in the database based on the order id. Therefore, every order id has different updates. But, i only can update the last item that i add to the order. And every previous orders that i have, will directly follow the update from the last item.
models.py
class OrderItem(models.Model):
Table_No = models.IntegerField(blank=False)
FoodId = models.TextField()
Item = models.TextField()
Qty = models.DecimalField(max_digits=5, decimal_places=0)
Price = models.DecimalField(max_digits=10, decimal_places=2)
TotalPrice = models.TextField()
Note = models.TextField(max_length=100, null=True)
OrderId = models.TextField(max_length=5, null=True)
FoodStatus = (
('1', 'Has been ordered'),
('2', 'cooked'),
('3', 'ready to be served'),
('4', 'done'),
)
food_status = models.CharField(max_length=50, choices=FoodStatus)
views.py
def kitchen_view(request):
chef_view = OrderItem.objects.all()
if request.method == "POST":
order_id = request.POST.get("OrderId")
status = OrderItem.objects.filter(OrderId=request.POST.get("OrderId"))
status.status1 = OrderItem.objects.update(food_status=request.POST.get("food_status"))
return render(request, 'restaurants/kitchen_page.html', {'chef_view': chef_view})
kitchen_page.html
<form action="#" method="post">
<style>
table, th, td {
border: 1px solid black;
}
</style>
{% csrf_token %}
{% for order in chef_view %}
<table width="800">
<tr>
<th width="800">Table Number</th>
<th width="800">Item</th>
<th width="800">Quantity</th>
<th width="800">Price</th>
<th width="800">Note</th>
<th width="800">Order Id</th>
<th width="800">Status</th>
</tr>
<tr>
<td width="800">{{ order.Table_No }}</td>
<td width="800">{{ order.Item }}</td>
<td width="800">{{ order.Qty }}</td>
<td width="800">{{ order.Price }}</td>
<td width="800">{{ order.Note }}</td>
<td width="800">{{ order.OrderId }}</td>
<td width="800">{{ order.food_status }}
<input type="text" name="food_status">
</tr>
</table>
{% endfor %}
<br><a href='' button onclick="myFunction()"><input type="submit" value="Change Status"></button>
</form>
The result should be able to update the food_status based on the order_id. Therefore, every order_id may have different food_status and show it to the template.
Anyone can help me to solve this problem? I really need the help to solve this issue. Really appreciate.
Ok so real problem is that your form is incorrect - you are not sending OrderId to view. Here's quickfix to it:
kitchen_page.html:
<style>
table, th, td {
border: 1px solid black;
}
</style>
<form action="#" method="post">
<table width="800">
<tr>
<th width="800">Table Number</th>
<th width="800">Item</th>
<th width="800">Quantity</th>
<th width="800">Price</th>
<th width="800">Note</th>
<th width="800">Order Id</th>
<th width="800">Status</th>
</tr>
{% csrf_token %}
{% for order in chef_view %}
<tr>
<td width="800">{{ order.Table_No }}</td>
<td width="800">{{ order.Item }}</td>
<td width="800">{{ order.Qty }}</td>
<td width="800">{{ order.Price }}</td>
<td width="800">{{ order.Note }}</td>
<td width="800">{{ order.OrderId }}</td>
<td width="800">{{ order.food_status }}
<input type="text" name="food_status" value="{{ order.food_status }}">
</tr>
<input type="hidden" name="OrderId" value="{{ order.OrderId }}">
{% endfor %}
</table>
<br><button type="submit" value="Change Status">Change Status</button>
</form>
views.py:
def kitchen_view(request):
if request.method == "POST":
order_ids = request.POST.getlist("OrderId")
food_statuses = request.POST.getlist("food_status")
for i in range(len(order_ids)):
OrderItem.objects.filter(OrderId=order_ids[i]).update(food_status=food_statuses[i])
chef_view = OrderItem.objects.all()
return render(request, 'restaurants/kitchen_page.html', {'chef_view': chef_view})
Previously stored filtered objects are not being updated as you have
status = OrderItem.objects.filter(OrderId=request.POST.get("OrderId"))
but when you are updating them, you should be updating the already filtered objects like
status = status.update(food_status=request.POST.get("food_status"))
Hope this helps.
You can update multiple objects at once including the filter in a single line as:
status = OrderItem.objects.filter(OrderId=request.POST.get("OrderId")).update(food_status=request.POST.get("food_status"))
The problem in your code:
status.status1 = OrderItem.objects.update(food_status=request.POST.get("food_status"))
was that you were not using the filter, instead you tried updating the status1 field(Can't see a status1 field in your model) using status.status1.

How do I get a list of the categories column, and then list of everything in a single view?

I want a navbar on top of my page with the categories in my model.
And when I click on the link to a category, I want a table that lists the items in that category.
For whatever reason I just can't get both things to work at the same time.
This is my model
from django.db import models
# Create your models here.
class menulist(models.Model):
name = models.CharField(max_length=120)
description = models.CharField(max_length=500)
price = models.DecimalField(decimal_places=1, max_digits=10, default=100.00)
category_choices = (
('breads', 'Breads'),
('cakes', 'Cakes'),
('hotfood', 'Hot Food'),
('porkrolls', 'Pork Rolls'),
('drinks', 'Drinks'),
('MISC', 'Misc'),
)
category = models.CharField(max_length=50, choices=category_choices, default='MISC',)
dateadded = models.DateField(auto_now_add=True)
dateupdated = models.DateField(auto_now=True)
img = models.ImageField(upload_to='products/', default='products/blank.jpg')
def __str__(self):
return self.name
This is the view:
class ProductAdminView(ListView):
template_name = 'menulistapp/product_admin.html'
def get_context_data(self, *, object_list=None, **kwargs):
context = super(ProductAdminView, self).get_context_data(**kwargs)
categorylist = menulist._meta.get_field('category').choices
context = {
"category_list": categorylist,
}
return context
def get_queryset(self):
slug = self.kwargs.get("slug")
if slug:
queryset = menulist.objects.filter(category__iexact=slug)
else:
queryset = menulist.objects.all()
return queryset
html template:
{% extends 'base.html' %}
{% block content %}
<div class="container ">
<ul class="nav nav-pills border-bottom border-top pt-2 pb-2">
{% for a, b in category_list %}
<li class="nav-item">
<a class="nav-link" href="/productadmin/{{ a }}">{{ b }}</a>
</li>
{% endfor %}
</ul>
</div>
<!-- tables -->
<div class="container">
<div class="row">
<table class="table table-striped table-hover ">
<thead class="thead-dark">
<tr>
<th style="width: 15%"scope="col"></th>
<th style="width: 55%" scope="col">Product Name</th>
<th scope="col">Category</th>
<th scope="col">Price</th>
<th scope="col">Date Added</th>
<th scope="col">Last Updated</th>
</tr>
</thead>
<tbody>
{% for obj in object_list %}
<tr>
<td class="align-middle"><img src="{{ obj.img.url }}" class="img-fluid"></td>
<td class="align-middle">{{ obj }}</td>
<td class="align-middle">{{ obj.category }}</td>
<td class="align-middle">${{ obj.price }}</td>
<td class="align-middle">{{ obj.dateadded }}</td>
<td class="align-middle">{{ obj.dateupdated }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
{% endblock %}
Sometimes I can only get the list working if I comment out the nav bar, and vice versa.
I've looked at mixins, but that only confused me more and doesn't do anything.

Trying to query based on choice field django

I've been stuck on this all day. I've got a model, Load, within that model it has a choice field with different "statuses". I am trying to implement some tabbed views in my template. So basically each tab will be responsible for displaying a certain status. I believe that I should be using a queryset within my view get_context_data but I'm just not really understanding how to accomplish this. I've tried a ton of different ways in the view, so i'll just paste the latest attempt.
These query's will be static once they are done so my best thought was to use a model managers for each query, but I couldn't get multiple model managers to work on one model. Here's an example of one. Any help would be appreciated. Thank you
class BookedManager(models.Manager):
def get_queryset(self):
return super(BookedManager, self).get_queryset().filter(load_status='Booked')
Models.py
class Load(models.Model):
load_number = models.IntegerField()
agent = models.ForeignKey(User,
limit_choices_to={'groups__name': 'Agent'},related_name='Agent', on_delete=models.CASCADE, null=True)
customer = models.ForeignKey(User,
limit_choices_to={'groups__name': 'Customer'},related_name='Customer', on_delete=models.CASCADE)
carrier = models.ForeignKey(Carrier, on_delete=models.CASCADE, blank=True, null=True)
pickup_date = models.DateField()
delivery_date = models.DateField()
shipper = models.ForeignKey(Location, related_name='shipper', on_delete=models.CASCADE, blank=True)
consignee = models.ForeignKey(Location, related_name='consignee', on_delete=models.CASCADE, blank=True)
po_number = models.CharField(max_length=255)
pu_number = models.CharField(max_length=255)
pieces = models.IntegerField()
description = models.TextField()
date_created = models.DateTimeField(auto_now_add=True)
PREBOOK = 'Waiting for Carrier'
BOOKED = 'Booked'
CONFIRMED = 'Confirmed Rate'
PICKED = 'Picked'
DELIVERED = 'Delivered'
INVOICED = 'Invoiced'
PAID = 'Paid'
LOAD_STATUS_CHOICES = (
(PREBOOK, 'Waiting for Carrier'),
(BOOKED, 'Booked'),
(CONFIRMED, 'Signed Rate Confirmation'),
(PICKED, 'Picked Up'),
(DELIVERED, 'Delivered'),
(INVOICED, 'Invoiced'),
(PAID, 'Paid'),
)
load_status = models.CharField(max_length=30, choices=LOAD_STATUS_CHOICES, default=PREBOOK)
def save(self, *args, **kwargs):
LoadUpdateHistory.objects.create(your_model=self, updated=timezone.now())
def get_absolute_url(self):
return reverse('loads:detail',kwargs={'pk':self.pk})
def __str__(self):
return str(self.load_number)
views.py
class LoadListView(ListView):
model = Load
context_object_name = 'loads'
def get_context_data(self, **kwargs):
context = super(LoadListView, self).get_context_data(**kwargs)
context['booked'] = Load.objects.filter(load_status__contains='booked')
return context
Template
{% for load in loads %}
<tr>
<td>{{load.load_number}}</td>
<td>{{load.agent}}</td>
<td>{{user.customer.company_name}}</td>
<td>{{load.carrier}}</td>
<td>{{load.pickup_date}}</td>
<td>{{load.delivery_date}}</td>
<td>{{load.shipper}}</td>
<td>{{load.consignee}}</td>
<td>{{load.po_number}}</td>
<td>{{load.pu_number}}</td>
<td>{{load.date_created}}</td>
<td>
<a href="#">
<button class="btn btn-warning" type="button">
<span class="glyphicon glyphicon-pencil"></span> </button>
</a>
<a href="{% url 'loads:delete' pk=load.pk%}">
<button class="btn btn-danger" type="button">
<span class="glyphicon glyphicon-remove"></span> </button>
</a>
</td>
</tr>
{% endfor %}
Update 1/21/17
Views.py
class LoadListView(ListView):
model = Load
context_object_name = 'loads'
def get_context_data(self, **kwargs):
context = super(LoadListView, self).get_context_data(**kwargs)
"""
This was probably my biggest mistake, I kept trying to query from
Load.load_status, load_status doesn't have a choice, it holds a variable
which then holds a status.
which i'm assuming is why i can't query off of the object load_status.
This new Loop says for the first choice in Load.LOAD_STATUS_CHOICES.
I'm not really understanding why we are selecting the first choice here.
"""
statuses = (choice[0] for choice in Load.LOAD_STATUS_CHOICES)
"""
Then we pass in loads_by_status into the template it filters the load_status
object and gets the status in statuses.
"""
context['loads_by_status'] = {
status: Load.objects.filter(load_status=status) for status in statuses
}
return context
My result in adding this code is that the template is not returning anything so I must be calling the data wrong in the template.
Template
<div>
<!-- Nav tabs -->
<ul class="nav nav-tabs" role="tablist" id='myTab'>
<li role="presentation" class="active">All Loads</li>
<li role="presentation">Waiting For Carrier</li>
<li role="presentation">Booked</li>
<li role="presentation">Confirmed</li>
<li role="presentation">Picked</li>
<li role="presentation">Delivered</li>
<li role="presentation">Invoiced</li>
<li role="presentation">Paid</li>
</ul>
<!-- Tab panes -->
<div class="tab-content">
<div role="tabpanel" class="tab-pane fade in active" id="allLoads">
<h1>All Loads</h1>
<table id="example" class="table table-striped table-bordered" cellspacing="0"
width="100%">
<thead>
<tr>
<th>Load Number</th>
<th>Load Status</th>
<th>Agent</th>
<th>Customer</th>
<th>Carrier</th>
<th>Pickup Date</th>
<th>Delivery Date</th>
<th>Shipper</th>
<th>Consignee</th>
<th>PO Number</th>
<th>PU Number</th>
<th>Date Created</th>
<th>Action</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Load Number</th>
<th>Load Status</th>
<th>Agent</th>
<th>Customer</th>
<th>Carrier</th>
<th>Pickup Date</th>
<th>Delivery Date</th>
<th>Shipper</th>
<th>Consignee</th>
<th>PO Number</th>
<th>PU Number</th>
<th>Date Created</th>
<th>Action</th>
</tr>
</tfoot>
<tbody>
{% for load in loads %}
<tr>
<td>{{load.load_number}}</td>
<td>{{load.load_status}}</td>
<td>{{load.agent}}</td>
<td>{{user.customer.company_name}}</td>
<td>{{load.carrier}}</td>
<td>{{load.pickup_date}}</td>
<td>{{load.delivery_date}}</td>
<td>{{load.shipper}}</td>
<td>{{load.consignee}}</td>
<td>{{load.po_number}}</td>
<td>{{load.pu_number}}</td>
<td>{{load.date_created}}</td>
<td>
<a href="#">
<button class="btn btn-warning" type="button">
<span class="glyphicon glyphicon-pencil"></span> </button>
</a>
<a href="#">
<button class="btn btn-danger" type="button">
<span class="glyphicon glyphicon-remove"></span> </button>
</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<div role="tabpanel" class="tab-pane fade" id="waitingForCarrier">
<h1>Waiting For Carrier</h1>
<table id="example" class="table table-striped table-bordered" cellspacing="0"
width="100%">
<thead>
<tr>
<th>Load Number</th>
<th>Load Status</th>
<th>Agent</th>
<th>Customer</th>
<th>Carrier</th>
<th>Pickup Date</th>
<th>Delivery Date</th>
<th>Shipper</th>
<th>Consignee</th>
<th>PO Number</th>
<th>PU Number</th>
<th>Date Created</th>
<th>Action</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Load Number</th>
<th>Load Status</th>
<th>Agent</th>
<th>Customer</th>
<th>Carrier</th>
<th>Pickup Date</th>
<th>Delivery Date</th>
<th>Shipper</th>
<th>Consignee</th>
<th>PO Number</th>
<th>PU Number</th>
<th>Date Created</th>
<th>Action</th>
</tr>
</tfoot>
<tbody>
{% for status, load in loads_by_status.items %}
<tr>
<td>{{load.load_number}}</td>
<td>{{load.load_status}}</td>
<td>{{load.agent}}</td>
<td>{{user.customer.company_name}}</td>
<td>{{load.carrier}}</td>
<td>{{load.pickup_date}}</td>
<td>{{load.delivery_date}}</td>
<td>{{load.shipper}}</td>
<td>{{load.consignee}}</td>
<td>{{load.po_number}}</td>
<td>{{load.pu_number}}</td>
<td>{{load.date_created}}</td>
<td>
<a href="#">
<button class="btn btn-warning" type="button">
<span class="glyphicon glyphicon-pencil"></span> </button>
</a>
<a href="#">
<button class="btn btn-danger" type="button">
<span class="glyphicon glyphicon-remove"></span> </button>
</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<div role="tabpanel" class="tab-pane fade" id="booked">
<h1>Booked</h1>
<table id="example" class="table table-striped table-bordered" cellspacing="0"
width="100%">
<thead>
<tr>
<th>Load Number</th>
<th>Load Status</th>
<th>Agent</th>
<th>Customer</th>
<th>Carrier</th>
<th>Pickup Date</th>
<th>Delivery Date</th>
<th>Shipper</th>
<th>Consignee</th>
<th>PO Number</th>
<th>PU Number</th>
<th>Date Created</th>
<th>Action</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Load Number</th>
<th>Load Status</th>
<th>Agent</th>
<th>Customer</th>
<th>Carrier</th>
<th>Pickup Date</th>
<th>Delivery Date</th>
<th>Shipper</th>
<th>Consignee</th>
<th>PO Number</th>
<th>PU Number</th>
<th>Date Created</th>
<th>Action</th>
</tr>
</tfoot>
<tbody>
{% for status, load in loads_by_status.items %}
<tr>
<td>{{load.load_number}}</td>
<td>{{load.load_status}}</td>
<td>{{load.agent}}</td>
<td>{{user.customer.company_name}}</td>
<td>{{load.carrier}}</td>
<td>{{load.pickup_date}}</td>
<td>{{load.delivery_date}}</td>
<td>{{load.shipper}}</td>
<td>{{load.consignee}}</td>
<td>{{load.po_number}}</td>
<td>{{load.pu_number}}</td>
<td>{{load.date_created}}</td>
<td>
<a href="#">
<button class="btn btn-warning" type="button">
<span class="glyphicon glyphicon-pencil"></span> </button>
</a>
<a href="#">
<button class="btn btn-danger" type="button">
<span class="glyphicon glyphicon-remove"></span> </button>
</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
You don't need a custom model manager for those queries at all. You can accomplish this sending the loads grouped by status to the template:
class LoadListView(ListView):
# ...
def get_context_data(self, **kwargs):
context = super(LoadListView, self).get_context_data(**kwargs)
statuses = (choice[0] for choice in Load.LOAD_STATUS_CHOICES)
context['loads_by_status'] = {
status: Load.objects.filter(load_status=status) for status in statuses
}
return context
Template:
{% for status, loads in loads_by_status.items %}
<h4>Status: {{ status }}</h4>
<table>
<thead>
<tr>
<th>Load number</th>
...
</tr>
</thead>
<tbody>
{# remember, loads is a queryset at this point #}
{% for load in loads %}
<tr>
<td>{{ load.load_number }}</td>
...
</tr>
{% endfor %}
</tbody>
</table>
{% endfor %}