Django : Previous and next week button - django

I am creating a timesheet application. I want to display timesheet on a weekly basis, which I am able to do.
I have create previous and next week button.
what approach should I use, so that when someone clicks on previous week, it shows timsheet for previous week and same for next week.
note - I have a timesheet table that contains one entry per day for time entry.
models.py --
class TimeRecords(models.Model):
emp_id = models.IntegerField(verbose_name = 'Employee ID')
ts_date = models.DateField(null=False, blank=False,verbose_name = 'Time Sheet Date')
ts_effort = models.PositiveIntegerField(default=8,verbose_name = 'Hours worked')
ts_desc = models.CharField(max_length=200,verbose_name = 'Time Description')
class Meta:
verbose_name = 'Time Records'
verbose_name_plural = 'Time Records'
unique_together = (("emp_id", "ts_date"),)
ordering = ["-emp_id"]
def __str__(self):
return self.ts_desc
forms.py ---
class CreateTimeSheetForm(forms.ModelForm):
emp_id = forms.IntegerField(widget=forms.HiddenInput(), initial=123)
class Meta:
model = TimeRecords
fields = '__all__'
labels = {
"ts_desc": "Task Description"
}
widgets = {
'ts_date': forms.TextInput(attrs={'readonly': True}),
}
views.py ---
def dateEnds():
date=datetime.date.today()
year, week, dow = date.isocalendar()
if dow == 1:
start_date = date
else:
start_date = date - timedelta(dow)
end_date = start_date + datetime.timedelta(days=7)
return start_date ,end_date
def daterange():
start_date, end_date=dateEnds()
for n in range(int((end_date - start_date).days)):
yield start_date + timedelta(n)
def timeEntryList(request):
start_date, end_date=dateEnds()
time_records=TimeRecords.objects.filter(emp_id=emp_id,ts_date__range=
(start_date, end_date))
context = {'time_records': time_records}
return render(request, 'timesheets/list.html', context)
list.html --
<tr> <th > Date</th> <th> Efforts</th> <th> Description</th> <th> Action</th> </tr>
{% for time_record in time_records %}
<tr>
<td >{{ time_record.ts_date|date:"SHORT_DATE_FORMAT" }}</td>
<td>{{ time_record.ts_effort }}</td>
<td>{{ time_record.ts_desc }}</td>
<td >Edit Delete</td>
</tr>
{% endfor %}
</table>
<a href="/timesheets/view" ><button type="button" class="btn" >Previous Week</button></a>

This is how I would approach this problem.
In models.py,
class TimeRecord(models.Model):
ts_date = models.DateTimeField()
# Other fields
def get_week(self):
return self.ts_date.isocalendar()[1]
In the views.py I would use list comprehensions to get time records for previous week and next week.
from django.utils import timezone
def my_view(request):
context = dict()
time_records = TimeRecord.objects.all()
current_week = timezone.now().isocalendar()[1]
current_records = [time_record for time_record in time_records if time_record.get_week() == current_week]
if request.method == 'POST':
week = request.POST['week']
if week == 'next-week':
current_records = [time_record for time_record in time_records if
time_record.get_week() == current_week + 1]
if week == 'last-week':
current_records = [time_record for time_record in time_records if
time_record.get_week() == current_week - 1]
context['current_records'] = current_records
return render(request, 'my.html', context)
Finally in the templates I would used hidden form inputs for next week and previous week.
<div>
{% for record in current_records %}
<p># {{ forloop.counter }} {{ record.ts_date }}</p>
{% endfor %}
<form action="" method="post">
{% csrf_token %}
<input type="hidden" name="week" value="next-week">
<button type="submit">next week</button>
</form>
<form action="" method="post">
{% csrf_token %}
<input type="hidden" name="week" value="last-week">
<button type="submit">last week</button>
</form>
</div>

Related

How can I capture the name or reg_no of the book in this list?

I'm working on a library system. I am unable to get the registration number of a book/books to be returned back to library...
My intention is to click on Return which captures the book name for return processing.. With what I have, when I print(book) it returns None meaning nothing has been taken from the click
My models
class Books(models.Model):
DEPARTMENT = (
('COM', 'Computer'),
('ELX', 'Electronics'),
('CIV', 'Civil'),
('BBS', 'Business'),
('MSC', 'Miscellaneous'),
)
reg_no = models.CharField(max_length=20, blank=True)
book_name = models.CharField(max_length=200)
no_of_books = models.IntegerField()
book_detail = models.TextField(default='text')
department = models.CharField(max_length=3, choices=DEPARTMENT)
def Claimbook(self):
if self.no_of_books>1:
self.no_of_books=self.no_of_books-1
self.save()
else:
print("not enough books to Claim")
def Addbook(self):
self.no_of_books=self.no_of_books+1
self.save()
def __str__(self):
return self.book_name
class Return(models.Model):
return_date = models.DateField(default=datetime.date.today)
borrowed_item = models.ForeignKey(Issue,on_delete=models.CASCADE)
def new_issue(request):
if request.method == 'POST':
i_form = IssueForm(request.POST)
if i_form.is_valid():
name = i_form.cleaned_data['borrower_id']
book = i_form.cleaned_data['book_id']
i_form.save(commit=True)
books = Books.objects.get(book_name=book)#Get a book names as selected in the dropdown
semest = Student.objects.get(name=name).semester#Get a student with a semester as selected in the dropdown
departm = Student.objects.get(name=name).depart
Books.Claimbook(books)
return redirect('new_issue')
else:
i_form = IssueForm()
semest = None
departm = None
sem_book = Semester.objects.filter(sem=semest, depart=departm)
return render(request, 'libman/new_issue.html', {'i_form': i_form, 'sem_book': sem_book})
The return view
def return_book(request):
book = request.GET.get('book_pk')
print(book)
books = Books.objects.get(id=book)
#b_id = r_form.cleaned_data['borrower_id']
Books.Addbook(books)
Issue.objects.filter(borrower_id=1, id=book).delete()
return render(request,'libman/view_issue.html',{'issue':issue})
The template that displays the borrowed books with a link to return beside each book.
{% if issue %}
<table class="layout">
<thead>
<th>Reg No.</th>
<th>Student Name</th>
<th>Book Name</th>
<th>Issue Date</th>
<th>Action</th>
</thead>
{% for borrow in issue %}
<tr>
<td>{{ borrow.borrower_id.student_id }}</td>
<td>{{ borrow.borrower_id }}</td>
<td>{{ borrow.book_id }}</td>
<td>{{ borrow.issue_date }}</td>
<td name='book_pk'>Return </td>
</tr>
{% endfor %}
</table>
{% else %}
<p> There are no books registered. </p>
{% endif %}
Issue model
class Issue(models.Model):
borrower_id = models.ForeignKey(Student,on_delete=models.CASCADE)
book_id = models.ForeignKey(Books,on_delete=models.CASCADE)
issue_date = models.DateField(default=datetime.date.today)
def __str__(self):
return str(self.book_id)
if i understood correctly - I believe you need to pass the borrow.book_id to the return view. so the return view knows which book you want return
in your template add the variable book_pk as follows
<td name='book_pk'>Return </td>
also you need to update your urls.py file to accept the new variable something like this
urlpatterns = [
path('returnbook/<book_pk>/', return_book),
]
but the above will need to also update your view function to handle the new passed argument and fetch the object etc..
def return_book(request,book_pk):
Or
you can add a form with a submit button
<form action="{% url 'return_book' %}">
<label for="book_id">Borrowed Book_id</label>
<input type="text" id="book_id" name="book_pk" value="{{ borrow.book_id }}" disabled><br><br>
<input type="submit" value="Submit">
</form>
it should work with your current code i think

How can i get data from multiple table in django

how can i get data from this below django html template
<form action="{% url 'purchase_order_item' p_order.id %}" method="post" enctype="multipart/form-data" class="form-group">
{% csrf_token %}
<table id="example-datatable" class="table table-vcenter table-condensed table-bordered">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Brand Name</th>
<th>Product Type</th>
<th>Category</th>
<th>SubCategory</th>
<th>Quantity</th>
<th>Unit Price</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{% for p in product %}
<tr>
<td>{{p.id}}</td>
<td>
{{p.name}}
</td>
<td>{{p.brand}}</td>
<td>{{p.ptype}}</td>
<td>{{p.catname}}</td>
<td>{{p.supplier}}</td>
<td>
<input type="text" id="quantity" name="quantity" value="1" class="form-control">
</td>
<td>
<input type="text" id="unitprice" name="unitprice" value="1" class="form-control">
</td>
<td>
<button type="submit" class="btn btn-primary btn-xs">Add</button>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</form>
views.py
def purchase_order_item(request,id):
now = datetime.datetime.now()
year = now.year
month = now.month
day = now.day
if (len(str(day))) == 1:
day = '0' + str(day)
if (len(str(month))) == 1:
month = '0' + str(month)
date = str(year) + '-' + str(month) + '-' + str(day)
randstrn = ""
for i in range(5):
randstrn = randstrn + random.choice(string.digits)
# catid = Cat.objects.get(name=name).pk
# news = News.objects.filter(ocatid=catid) # showing post based on master category
supplier = Supplier.objects.all()
p_order = Purchase_order.objects.get(pk=id)
product = Parts.objects.all()
# this is the form for getting data from html
if request.method == 'POST':
quantity = request.POST.get('quantity')
unit_price = request.POST.get('unitprice') # itemid = pk type
nameid = request.POST.get('quantity')
ref_num = Purchase_order.objects.get(pk=id).order_id
order_id = Purchase_order.objects.get(pk=id).order_id # get Purchase Order Id for Relational Referance
sv = Purchase_order_item(
ref_number=ref_num,
product_name='sample_name',
# product_brand='product_brand',
# product_type = 'product_type',
# product_cat = 'product_cat',
# product_sub_cat = 'k',
quantity=quantity,
unit_price = unit_price,
total_price = '12',
order_id=order_id
)
sv.save()
# return redirect('purchase_order_item_list')
return render(request,'back/purchase/assign_purchas_item.html',
{'p_order':p_order,'supplier':supplier,
'product':product}
)
This is my Models.py
class Purchase_order_item(models.Model):
# order_id = models.IntegerField(default=0) # this is a purchase order id for referance purpose and relation both
ref_number = models.IntegerField(default=0)
product_name = models.CharField(max_length=50) # generate an unique Rendome number for farther relation for invoice item
product_brand = models.CharField(max_length=50)
product_type = models.CharField(max_length=50) # genuine or after market
product_cat = models.CharField(max_length=50) # product name
product_sub_cat = models.CharField(max_length=50) # product name
quantity = models.IntegerField(default=0)
unit_price = models.FloatField(default=250)
total_price = models.FloatField()
order_id = models.IntegerField(default=0)
This is my Html screenshot
Now my question is that ..
how can i get all the listed data after click add button as like Name , brand name , product type , category , subcat , quantity , unit price , etc save to purchase_order_item table .
thanks in advance

Updating model field after input in Django

I am trying to update an account value model field after the user inputs a stock price and quantity from a form. Essentially the user would input a stock price and share quantity and their account balance should reflect the purchase amount. Below are images of my models.py, my forms.py, my views.py and my buy_stock.html page. Any insight as to how I can get the value to save would be very helpful. Thanks in advance. - Total newb
Views.py
from django.shortcuts import render, redirect
from .models import Stock, Bank, BuyStockModel
from .forms import StockForm, BankForm, BuyStock, Registration
from django.contrib import messages
import requests
import json
def main(request):
stocks = BuyStockModel.objects.all().order_by('-created')
form = BuyStock()
account = Bank.objects.only('account')
balance = account
if request.method == 'POST':
price = request.POST.get('price')
quantity = request.POST.get('quantity')
if price is not None:
price = float(price)
if quantity is not None:
quantity = float(quantity)
total = float(price) * float(quantity)
if balance >= total:
balance = balance - total
account.update(account = balance)
#account.save()
ticker = request.POST['ticker']
api_request = requests.get(
"https://cloud.iexapis.com/stable/stock/" +
ticker +
"/quote?token=i_should_get_a_new_one"
)
try:
api = json.loads(api_request.content)
except Exception as e:
api = "Error..."
context = {
'api': api,
'form' : form,
'stocks' : stocks,
"account" : account
}
return render(request, 'buy_stock.html', context)
else:
context = {'form' : form, 'stocks' : stocks}
return render(request, 'buy_stock.html', context)
def buy_stock(request):
print('buy_stock')
if request.method == 'GET':
form = BuyStock()
stocks = BuyStockModel.objects.all().order_by('-created')
output = {'form' : form, 'stocks' : stocks}
return render(request, 'buy_stock.html', output)
elif request.method == 'POST':
form = BuyStock(request.POST or None)
if form.is_valid():
form.save()
name = form.cleaned_data['name']
price = form.cleaned_data['price']
quantity = form.cleaned_data['quantity']
form = BuyStock()
return redirect('buy_stock')
return render(request, 'buy_stock.html', {
'form' : form,
'name' : name,
'price' : price,
'quantity' : quantity
})
Models.py
from django.db import models
class Stock(models.Model):
ticker = models.CharField(max_length = 10)
def __str__(self):
return self.ticker
class Bank(models.Model):
account = models.DecimalField(
max_digits = 15, default = 30000.0, decimal_places = 0,
editable = True
)
def __str__(self):
return self.account
class BuyStockModel(models.Model):
name = models.CharField(max_length = 100)
option = models.CharField(max_length = 10, default = 'buy')
price = models.DecimalField(
max_digits = 15, decimal_places = 2, default = 0
)
quantity = models.DecimalField(
max_digits = 15, decimal_places = 0, default = 0
)
total_value = models.DecimalField(
max_digits = 15, default = 1, decimal_places = 0,
editable = True
)
created = models.DateTimeField(auto_now_add = True)
def __str__(self):
return self.price
def __str__(self):
return self.quantity
def calc_total(self):
amount = (self.price * self.quantity)
return amount
def save_total(self):
self.total_value = self.calc_total()
super(BuyStockModel, self).save()
Forms.py
from django import forms
from .models import Stock, Bank, BuyStockModel
from django.contrib.auth import login, authenticate
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class Registration(UserCreationForm):
email = forms.EmailField()
class Meta:
model = User
fields = ["username", "email", "password1", "password2"]
class StockForm(forms.ModelForm):
class Meta:
model = Stock
fields = ["ticker"]
class BankForm(forms.ModelForm):
class Meta:
model = Bank
fields = ["account"]
class BuyStock(forms.ModelForm):
class Meta:
model = BuyStockModel
fields = ["name", "price", "quantity"]
widgets = {
'name' : forms.TextInput(attrs = {'class' : 'form-control'}),
'price' : forms.TextInput(attrs = {'class' : 'form-control'}),
'quantity' : forms.TextInput(attrs = {'class' : 'form-control'}),
}
buy_stock.html
{% extends 'base.html' %}
{% block content %}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Project-4 Buy Stock page</title>
</head>
<body>
<div class="container"></div>
<h1>Buy Stock</h1>
<br/>
<div>
<form action = "{%url 'main' %}" class="form-inline my-2 my-lg-0" method = "POST">
{% csrf_token %}
<input class="form-control mr-sm-2" type="search" placeholder="Get Stock Quote" aria-label="Search" name = "ticker">
<button class="btn btn-outline-secondary my-2 my-sm-0" type="submit">Stock Quote</button>
</form>
</div>
<br/>
<br/>
<div>
{% if ticker %}
{{ ticker }}
{% endif %}
{% if api %}
{% if api == "Error..." %}
There was a problem with your ticker symbol,
please try again...
{% else %}
<h2>{{ api.companyName }}</h2>
<br/>
{% load humanize %}
Price: ${{ api.latestPrice|intcomma }}<br/>
Previous Close: ${{ api.previousClose|intcomma }}<br/>
Market Cap: ${{ api.marketCap|intcomma }}<br/>
YTD Change: {{ api.ytdChange }}<br/>
52 Week High: ${{ api.week52High|intcomma }}<br/>
52 Week Low: ${{ api.week52Low|intcomma }}<br/>
<br/>
{% endif %}
{% else %}
{% endif %}
</div>
<br/>
<div>
<h6 class = "bold">Total in Account</h6>
{% for item in account %}
{% load humanize %}
<h1 class = "bold">${{ item.account|intcomma }}</h1>
{% endfor %}
</div>
<div class="container">
<div class="row">
<div class="col-sm">
<div class = "form-group">
<form action = "{%url 'buy_stock' %}" method = "POST">
{% csrf_token %}
{{ form.as_p }}
<div class="dropdown">
<div class="dropdown">
<button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenu2" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Trading Options
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenu2">
<button class="dropdown-item" type="sumbit">Buy</button>
<button class="dropdown-item" type="submit">Sell</button>
</div>
</div>
</form>
</div>
</div>
<div class="row">
<div class="col-sm">
<table class="table table-striped table-bordered table-hover">
<thead class="thead-dark">
<tr>
<th scope="col">Date Purchased</th>
<th scope="col">Company Name</th>
<th scope="col">Stock Price</th>
<th scope="col">Shares Purchased</th>
</tr>
</thead>
<tbody>
{% for item in stocks %}
<tr>
{% load humanize %}
<th scope="row">{{ item.created }}</th>
<td>{{ item.name }}</td>
<td>${{ item.price|intcomma }}</td>
<td>{{ item.quantity|intcomma }} Shares</td>
</tr>
{% endfor %}
</tbody>
</table>
<br/>
{% for item in stocks %}
<a class="btn btn-danger" href = "{% url 'sell_stock' item.id %}">Delete {{ item.name }}</a>
{% endfor %}
</div>
</div>
</div>
</div>
</div>
<br/>
<br/>
<br/>
</body>
{% endblock %}
I think you should learn first about model relations. You data model will not work this way and fixing that, the rest will become more clear, hopefully.
An Order (you call it BuyStockModel) is the marriage of a product with a customer. So this order model should have links with the product (Stock) and the Customer (in your case represented by their Bank account). A broker has 2-way orders: both sales and purchase orders, but for the basic data model it's not important.
I'm going to use Order below, because BuyStockModel is not a good name for me :).
So you need two relations:
Order
/ \
Stock Bank
Django uses ForeignKeys for this relation:
class Order(models.Model):
stock = models.ForeignKey(Stock, on_delete=models.PROTECT)
account = models.ForeignKey(Bank, on_delete=models.PROTECT)
option = models.CharField(max_length = 10, default = 'buy')
price = models.DecimalField(
max_digits = 15, decimal_places = 2, default = 0
)
quantity = models.DecimalField(
max_digits = 15, decimal_places = 0, default = 0
)
created = models.DateTimeField(auto_now_add = True)
#property
def total_value(self):
return self.price * self.quantity
def __str__(self):
return (
f"{self.option.upper()}: {self.id} / qt: {self.quantity}"
f" / price: {self.price}"
)
You can now construct a single "OrderForm" using the Order model, that can render the accounts and stock tickers. That should get you on your way.

Django class based view to query database from form and display results

So I am completely new to Django, I want to have a user enter a keyword into an HTML form then have each row from the database where an attribute matches that keyword displayed on the page. I've tried various ways of doing this and am not sure what I am doing wrong. Any help would be appreciated.
search.html
<div class="container">
<form method="GET" action="{% url 'search' %}">
<div class="form-group">
<input type="text" name="make" placeholder="Car Make" />
<label>
<button type="submit" class="btn btn-danger"> Go </button>
</label>
</div>
</form>
{% if results %}
<table>
<tr>
<th scope="col"></th>
<th scope="col">Car Make</th>
<th scope="col">Car Model</th>
<th scope="col">Car Type</th>
<th scope="col">Number of Seats</th>
<th scope="col">Price</th>
</tr>
{% for item in results%}
<tr>
<td>{{item.makename}}</td>
<td>{{item.model}}</td>
<td>{{item.seriesname}}</td>
<td>{{item.seatingcapacity}}</td>
<td>{{item.pricenew}}</td>
</tr>
{% endfor %}
</table>
{% endif %}
</div>
views.py
class SearchView(TemplateView):
template_name = 'carproject/search.html'
model = Vehicles
def get(self, request):
form = AdvancedSearch()
return render(request, self.template_name, {'form': form})
def search(self, request):
makequery = self.request.GET.get['make']
if makequery:
results = self.Vehicles.objects.filter(makename__icontains(makequery))
return render(request, self.template_name, {'results': results})
Models.py
class Vehicles(models.Model):
carid = models.IntegerField(db_column='CarID', primary_key=True)
makename = models.CharField(db_column='MakeName', max_length=45)
model = models.CharField(db_column='Model', max_length=45)
seriesname = models.CharField(db_column='SeriesName', max_length=45)
seriesyear = models.TextField(db_column='SeriesYear')
pricenew = models.IntegerField(db_column='PriceNew')
fuelsystem = models.CharField(db_column='FuelSystem', max_length=45)
enginesize = models.CharField(db_column='EngineSize', max_length=10)
tankcapacity = models.CharField(db_column='TankCapacity', max_length=10)
power = models.CharField(db_column='Power', max_length=10)
seatingcapacity = models.IntegerField(db_column='SeatingCapacity')
standardtransmission = models.CharField(db_column='StandardTransmission', max_length=45)
bodytype = models.CharField(db_column='BodyType', max_length=45)
drive = models.CharField(db_column='Drive', max_length=3)
wheelbase = models.CharField(db_column='WheelBase', max_length=10)
class Meta:
managed = False
db_table = 'vehicles'
You can just do Vehicles.objects.filter(makename__icontains=request.GET.get("make","somevalueasdefault")) in your get function. Maybe I am missing something, but I am not sure why you have rendered the view like that in a class-based view. Just as an example, you can do like below.
class SearchView(TemplateView):
template_name = "carproject/search.html"
def get(self, kwargs):
context = super(SearchView, self).get_context_data(**kwargs)
context['queryset'] = Vehicles.objects.filter(makename__icontains=request.GET.get("make","sdefault"))
return context

Select specific data in Django query and map the result (between th and td) in a table

I've been avoiding this way too many times and I think it's time to ask for some help.
First of all, I have the following structure of the relevant parts of my project:
# models.py
class LocationsProvisioning(models.Model):
user = models.CharField(max_length=200)
dates = models.CharField(max_length=15)
locations = models.CharField(max_length=200)
goods = models.CharField(max_length=200)
quantities = models.CharField(max_length=200)
samples = models.CharField(max_length=200)
# forms.py
DateInput = partial(forms.DateInput, {
'class': 'datepicker form-control',
'name': 'dates'})
class ReportForm(forms.Form):
start_date = forms.DateField(label="Start date", required=True,
widget=DateInput(),
initial=datetime.date.today() - datetime.timedelta(days=1))
end_date = forms.DateField(label="End date", required=True,
widget=DateInput(),
initial=datetime.date.today())
locations = forms.ModelMultipleChoiceField(label='Select some locations',
queryset=LocationsModel.objects.all().order_by('name'), required=True,
widget=forms.SelectMultiple(attrs={
'class': 'form-control',
'name': 'locations'
}))
# views.py
def reports_view(request):
form = ReportForm(request.POST or None)
selected_locations = ''
all_goods = GoodsModel.objects.all().order_by('name')
if request.method == "POST":
if form.is_valid():
start_date = str(form.cleaned_data.get('start_date'))
end_date = str(form.cleaned_data.get('end_date'))
selected_locations = form.cleaned_data.get('locations')
else:
form = ReportForm()
return render(request, 'admin/coffee_app/raport.html', {
'form': form,
'selected_locations': selected_locations,
'all_goods': all_goods # those will be the headers of the table
})
So far so good, I have in my template a table which contains as headers, goods, and as the first column the selected_locations.
The html looks like this (I've removed some html tags for readability):
<form class="form-horizontal" method="post">
{{ form.start_date.label_tag }}
{{ form.end_date.label_tag }}
{{ form.locations }}
<button type="submit" class="btn my-btn" />
</form>
<table id="example" class="table table-striped table-bordered table-hover" cellspacing="0" width="100%">
<thead>
<tr>
<th>Locations</th>
{% for good in all_goods %}
<th>{{ good }}</th>
{% endfor %}
<th>Samples</th>
</tr>
</thead>
<tbody>
{% for location in selected_locations %}
<tr>
<td>{{ location }}</td>
<td>{{ here_I_should_have_quantities (some kind of map between the selected location and the `good` }}</td>
<td>{{ here_I_should_have_probes_for_selected_locations }}</td>
</tr>
{% endfor %}
</tbody>
</table>
Now, I'd like to do some kind of select (LocationsProvisioning.objects.filter()) which should look like:
SELECT quantities, samples
FROM LocationsProvisioning
WHERE locations in selected_locations and dates BETWEEN start_date AND end_date
I know I can do something like:
LocationsProvisioning.objects.filter(dates__range=[start_date, end_date])
but I can't seem to find a way to do: SELECT quantities, samples FROM LocationsProvisioning WHERE locations in selected_locations
What looks impossible to me, is also match the quantities / probes only where needed:
Good_1 Good_2 Good_3 Good_4 Samples
locality_1 23 2 7 3
locality_2 3 40 7 5
locality_3 1 2 3
More details:
each selected_locality has a sample
a selected_locality might not have a value for all goods (see the above table)
PS: I couldn't find a better title for this, so feel free to edit it
Should dates be a CharField or DateField? Try this queryset to get the data.
LocationsProvisioning.objects
.filter(locations__in=selected_locations, dates__range=(start_date, end_date))
.values('quantities','samples')