class Product(models.Model):
name = models.CharField(max_length=50)
desc = models.CharField(max_length=50)
def __unicode__(self):
return self.name
class ProductModels(models.Model):
product = models.ForeignKey(Product)
name = models.CharField(max_length=50)
price = IntegerField(max_length=50)
def __unicode__(self):
return self.name
class Sold(model.Model)
product = models.ForeignKey(Product)
model_name = models.ForeignKey(ProductModels)
sold_date = models.DateField()
model_qty = models.IntegerField()
def __unicode__(self):
return self.sold_date
this is with reference to my previous question( that problem is solved)
what i am trying to find out is how many models have been sold from Jan to Dec for the particular product.
so far i have done this, i know it's little crude. but it would help he if it written correctly:
views.py
allmonths = ['jan' , ....., 'dec']
products = Products.objects.all()
for each_product in products :
models = ProductModels.objects.filter(product = each_product)
for each_model in models:
for months in allmonths :
att_name = str(each_model.model_name) + str(months)
print 'attname %s' % att_name
val = sold.objects.filter(product = each_product ,
model_name = each_model ,(sold_date =(allmonths.indesx(month) + 1))) .aggregate(qty=Sum('model_qty'))
val = temp(val['qty'])
setattr(each_product, att_name , val)
I am not sure if this correct or not , but this approach has worked earlier. i used getattribute template tag from here.
This is how my template looks like :
{% for record in products %}
<tr class="odd gradeX">
<td><span class="label label-warning">{{ record.name }}</span></td>
<td>
<table class="table table-striped table-bordered table-hover" id="pipelineTbl">
{% for model in record.ProductModels_set.all %}
<tr class="odd gradeX">
<td>
<span class="label label-success">{{ model }}</span>
</td>
</tr>
{% endfor %}
</table>
</td>
{% for months in allmonths %}
<td>
<table class="table table-striped table-bordered table-hover" id="pipelineTbl3">
{% for model in record.ProductModels_set.all %}
{% with model|add:months as val %}
<tr>
<td>{{ record|getattribute:val }}</td>
</tr>
{% endwith %}
{% endfor %}
</table>
</td>
{% endfor %}
</tr>
{% endfor %}
You can make the following query:
product = some_product()
year = 2013
product_sells = Sold.objects.filter(product=product, sold_date__year=year)
If you want to know how many individual sells do this:
product_sells.count()
If you want to sum the product sold quantities:
from django.db.models import Sum
product_sells.Sum('model_qty')
In general avoid iterating over Products.objects.all(), as it's really expensive on database and memory.
Related
its my first time to ask hope I can find solution to my problem. Am trying to display the courses in an html page using objects.all() but it returns nothing and the page remain empty, even though records do exist in the database. I tried the same method for other pages and it worked, idk what am doing wrong here :(
in view.py
def viewCourse(request):
corlist = Course.objects.all()
#print(muffin)
#course.count()
context = {'corlist':corlist}
return render(request, 'LogInApp/ViewCourse.html', context)
in model.py
class Course(models.Model):
COURSES = (
('Data Structure','Data Structure'),
('Computer Network','Computer Network'),
('Web Design','Web Design'),
('Internet of Things','Internet of Things'),
('Artificial Intelligence','Artificial Intelligence'),
('Artificial Intelligence-Tut', 'Artificial Intelligence-Tut'),
)
course_id = models.AutoField(primary_key=True)
course_name = models.CharField(max_length=100, null=True, choices= COURSES)
fk_lecturer_id = models.OneToOneField(Lecturer, on_delete=models.CASCADE) # foreign key
date = models.DateField(max_length=20, null=True)
time = models.TimeField(max_length=20, null=True)
def __str__(self):
return '{} {}'.format(self.course_id, self.course_name)
#property
def lecturerid(self):
return self.fk_lecturer_id.lecturerid
in ViewCourse.html
<table border="1" class="table">
<tr>
<th>Course ID</th>
<th>Course Name</th>
<th>Course Lecturer</th>
<th>Date</th>
<th>Time</th>
<th width="100px"> </th>
</tr>
{% for co in corlist %}
<tr>
<td> {{ co.course_id }} </td>
<td> {{ co.course_name }} </td>
<td> {{ co.fk_lecturer_id }} </td>
<td> {{ co.date }} </td>
<td> {{ co.time }} </td>
</tr>
{% endfor %}
</table>
I would like to show in my template in each cell the name ("nombre") of the client ("cliente") with his payment {{pago.cantidad_pagada}} , the problem is that as I am doing it {{presupuesto.cliente.nombre}}, I show all the names that I have in my table and they are repeated in each of the cells, I imagine that it is due to the use of "for", but I don't know of another way to display the data.
presupuestos.html
<tbody>
{% for pago in pagos %}
<tr>
<td>
{% for presupuesto in presupuestos %}
{{presupuesto.cliente.nombre}}
{% endfor %}
</td>
<td>
{{pago.cantidad_pagada}}
</td>
</tr>
{% endfor%}
</tbody>
pagos/models.py
class Pagos(models.Model):
numero_transaccion=models.IntegerField()
estimate=models.ForeignKey(Presupuestos, on_delete=models.SET_NULL, null=True)
def __str__(self):
return f'{self.numero_transaccion}'
presupuestos/models.py
class Presupuestos(models.Model):
cliente= models.ForeignKey(Clientes, on_delete=models.SET_NULL, null=True)
def __str__(self):
return f'{self.cliente}'
clientes/models.py
class Clientes(models.Model):
nombre = models.CharField(max_length=200, blank=True)
def __str__(self):
return f'{self.nombre}'
views.py
def presupuestosIndex(request):
presupuestos = Presupuestos.objects.all()
pagos=Pagos.objects.all()
return render(request, "Presupuestos/presupuestos.html", {'presupuestos':presupuestos,'pagos':pagos})
You have a foreign key estimate from Pagos to Presupuestos. If that's the relationship you wish to display for each pago you would do
<tbody>
{% for pago in pagos %}
<tr>
<td>
{{pago.estimate.cliente.nombre}}
</td>
<td>
{{pago.cantidad_pagada}} <! not in the models in the question -->
</td>
</tr>
{% endfor%}
</tbody>
i am working on hotel booking app , in this i want to display the image of a hotel, based on user entered location . In this if i am displaying all hotels , i am able to display an image , if i am trying to displaying an image through some CRUD operations, i am unable to display it. Here are my code snippets.
class Customer_details(models.Model):
Name = models.CharField(max_length=128)
Age = models.IntegerField()
Mobile_number = models.IntegerField()
Email = models.EmailField()
Address = models.CharField(max_length=50)
Special_request = models.CharField(max_length=50, blank=True)
user = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.Name
hotel_rating_choices = (
('1','1'),
('2','2'),
('3','3'),
('4','4'),
('5','5'),
('6','6'),
('7','7'),
)
class Hotel(models.Model):
Hotel_Name = models.CharField(max_length=50)
location = models.CharField(max_length=20)
no_of_rooms = models.IntegerField()
rating = models.CharField(max_length=1, choices=hotel_rating_choices, default=3)
hotel_img = models.ImageField(upload_to='hotel_images/')
uploaded_at = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.Hotel_Name
class Hotel_image(models.Model):
hotel_img = models.ImageField(upload_to = 'hotel_images/')
hotel = models.ForeignKey(Hotel, on_delete=models.CASCADE)
def __str__(self):
return self.hotel
Ignore the remaining models just concentrate on Hotel model .
`Below code snippet is my view regarding to query.
def get_hotels_by_location(request):
location = request.POST.get('location')
print(location)
location = location.lower()
result = Hotel.objects.values('Hotel_Name', 'rating', 'hotel_img').filter(location=location)
context = {'hotels': result, 'header': ['Hotel_Name', 'Rating', 'image'] }
return render(
request,
template_name='display_hotel_by_location.html',
context=context
)
And below is my django html template
<table class="table">
<tr>
{% for i in header %}
<th>
{{ i }}
</th>
{% endfor %}
</tr>
{% for element in hotels %}
<tr>
{% with i=0 %}
{% for key, value in element.items %}
{% if i == 2 %}
<td> <img src="{{ element.url }}" width = "300" height="300"> </td>
{% endif %}
<td> {{ value }} </td>
{% with j=i %}
j=j+1
i=j
{% endwith %}
{% endfor %}
</tr>
{% endfor %}
</table>
Please help me on this issue.
Change your Hotel_image class to add related name at your foreign to use it further
class Hotel_image(models.Model):
hotel_img = models.ImageField(upload_to = 'hotel_images/')
hotel = models.ForeignKey(Hotel, on_delete=models.CASCADE, related_name="hotel_images")
Clean up a bit your views, you dont really need use values in that case.
from .models import Hotel
def get_hotels_by_location(request):
location = request.POST.get('location').lower()
result = Hotel.objects.filter(location=location)
context = {'hotels': result, 'header': ['Hotel_Name', 'Rating', 'image'] }
return render(
request,
template_name='display_hotel_by_location.html',
context=context
)
HTML 1 - If you consuming the hotel_img from class Hotel use this one
<table class="table">
<tr>
{% for i in header %}
<th>{{ i }}</th>
{% endfor %}
</tr>
{% for hotel in hotels %}
<tr>
{% if forloop.counter0 == 2 and hotel.hotel_img %}
<td> <img src="{{ hotel.hotel_img.url }}" width="300" height="300"> </td>
{% endif %}
<td> {{ hotel.Hotel_Name }} </td>
</tr>
{% endfor %}
</table>
HTML 2 - If you using the class Hotel_image use like that
<table class="table">
<tr>
{% for i in header %}
<th>{{ i }}</th>
{% endfor %}
</tr>
{% for hotel in hotels %}
<tr>
{% for img in hotel.hotel_images %}
{% if img.hotel_img %}
<td> <img src="{{ img.hotel_img.url }}" width="300" height="300"> </td>
{% endif %}
{% endfor %}
<td> {{ hotel.Hotel_Name }} </td>
</tr>
{% endfor %}
</table>
More info about Django relations: https://docs.djangoproject.com/en/2.0/ref/models/fields/#django.db.models.ForeignKey.related_name
You can use Template Tags too to filter all images from your Hotel_Image
1 - Create one folder called templatetag and inside that one file inside it to be your templatetag inside your app folder
hotel/templatetags/hotel_templatetag.py
Inside the file put that code
from django import template
from .models import Hotel_image
register = template.Library()
def get_hotel_images(self):
return Hotel_image.objects.filter(id=self.id)
You Html should be like that
<table class="table">
<tr>
{% for i in header %}
<th>{{ i }}</th>
{% endfor %}
</tr>
{% for hotel in hotels %}
<tr>
{% for img in hotel|get_hotel_images %}
{% if img.hotel_img %}
<td> <img src="{{ img.hotel_img.url }}" width="300" height="300"> </td>
{% endif %}
{% endfor %}
<td> {{ hotel.Hotel_Name }} </td>
</tr>
{% endfor %}
</table>
More info about templatetags: https://docs.djangoproject.com/en/2.0/howto/custom-template-tags/
What I want to achieve is to have a list of associations on one column and total members on the other column, like so:
I have tried to look for other solutions here with no luck, is there something i'm missing?
Still a newbie so appreciate all your help and guidance, folks!
models.py
class Member(models.Model):
member_no = models.AutoField(primary_key=True)
association = models.ForeignKey('Association')
...
class Association(models.Model):
asoc_name = models.CharField(max_length=50, null=True, blank=True)
class Meta:
db_table = 'Association'
def __str__(self):
return self.asoc_name
def __unicode__(self):
return self.asoc_name
class AssociationSummary(Association):
class Meta:
proxy = True
verbose_name = 'Association Summary'
verbose_name_plural = 'Association Summary'
admin.py
#admin.register(AssociationSummary)
class ChartAssociationAdmin(admin.ModelAdmin):
change_list_template = 'admin/chart_association.html'
def get_total(self):
total = Member.objects.all().aggregate(association=Sum('member_no'))
return total
def changelist_view(self, request, extra_context=None):
my_context = {
'member_no': self.get_total(),
}
return super(ChartAssociationAdmin, self).changelist_view(request,
extra_context=my_context)
chart_association.html
{% extends 'admin/change_list.html' %}
{% block content_title %}
<h1> Association Summary </h1>
{% endblock %}
{% block result_list %}
<div class=”results”>
<table>
<thead>
<tr>
<th>
<div class=”text”>
<span>Association</span>
</div>
</th>
<th>
<div class=”text”>
<span>Total Members</span>
</div>
</th>
</tr>
</thead>
<tbody>
{% for row in member %}
<tr class="{% cycle 'row1' 'row2' %}">
<td> {{ row.asoc_name }} </td>
<td> {{ row.total }} </td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% endblock %}
{% block pagination %}{% endblock %}
I need help figuring out how to set up my html table in a way that is giving me issues if anyone can help me figure out how to fix it and make it look like the second picture would be awesome.
*Side note I am using Django
So first off I have three models that I will be using in this view/template. They are called Sheet, Dimension, Inspeciton_vals, my Dimension model has a forgien key called sheet_id which links to sheet, my Inspeciton_vals model has a foreign key that links to Dimension.
Here is my views.py
#login_required
def shipping(request, id):
sheet_data = Sheet.objects.get(pk=id)
work_order = sheet_data.work_order
customer_data = Customer.objects.get(id=sheet_data.customer_id)
customer_name = customer_data.customer_name
title_head = 'Shipping-%s' % sheet_data.work_order
complete_data = Sheet.objects.raw("""select s.id, s.work_order, d.target, i.reading, d.description, i.serial_number from app_sheet s left join app_dimension d on s.id = d.sheet_id
left join app_inspection_vals i on d.id = i.dimension_id""")
for c_d in complete_data:
dim_description = Dimension.objects.filter(sheet_id=c_d.id).values_list('description', flat=True).distinct()
dim_id = Dimension.objects.filter(sheet_id=c_d.id)[:1]
for d_i in dim_id:
dim_data = Inspection_vals.objects.filter(dimension_id=d_i.id)
sample_size = dim_data
return render(request, 'app/shipping.html',
{
'work_order': work_order,
'sample_size': sample_size,
'customer_name': customer_name,
'title': title_head,
'complete_data': complete_data,
'dim_description': dim_description,
})
here are my models
class Sheet(models.Model):
objects = SheetManager()
create_date = models.DateField()
updated_date = models.DateField()
customer_name = models.CharField(max_length=255)
part_number = models.CharField(max_length=255)
part_revision = models.CharField(max_length=255)
work_order = models.CharField(max_length=255)
purchase_order = models.CharField(max_length=255)
sample_size = models.IntegerField()
sample_scheme = models.CharField(max_length=255)
overide_scheme = models.IntegerField()
template = models.IntegerField()
sample_schem_percent = models.IntegerField()
critical_dimensions = models.IntegerField()
closed = models.IntegerField()
serial_index = models.CharField(max_length=255)
drawing_number = models.CharField(max_length=255)
drawing_revision = models.CharField(max_length=255)
heat_number = models.CharField(max_length=255)
note = models.CharField(max_length=255)
valc = models.CharField(max_length=255)
class Dimension(models.Model):
description = models.CharField(max_length=255)
style = models.CharField(max_length=255)
created_at = models.DateField()
updated_at = models.DateField()
target = models.IntegerField()
upper_limit = models.IntegerField()
lower_limit = models.IntegerField()
inspection_tool = models.CharField(max_length=255)
critical = models.IntegerField()
units = models.CharField(max_length=255)
metric = models.CharField(max_length=255)
target_strings = models.CharField(max_length=255)
ref_dim_id = models.IntegerField()
nested_number = models.IntegerField()
met_upper = models.IntegerField()
met_lower = models.IntegerField()
valc = models.CharField(max_length=255)
sheet = models.ForeignKey(Sheet, on_delete=models.CASCADE, default=DEFAULT_FOREIGN_KEY)
class Inspection_vals(models.Model):
created_at = models.DateField()
updated_at = models.DateField()
reading = models.IntegerField(null=True)
reading2 = models.IntegerField(null=True)
reading3 = models.IntegerField(null=True)
reading4 = models.IntegerField(null=True)
state = models.CharField(max_length=255)
state2 = models.CharField(max_length=255)
state3 = models.CharField(max_length=255)
state4 = models.CharField(max_length=255)
approved_by = models.CharField(max_length=255)
approved_at = models.DateField(null=True, blank=True)
dimension = models.ForeignKey(Dimension, on_delete=models.CASCADE, default=DEFAULT_FOREIGN_KEY)
serial_number = models.IntegerField(default=1)
Finally here is my template What I want to do is have my header be the serial numbers. This will be based off sample_size on my sheet model so lets say I have 24 as a sample size show 20 horizontal rows. Next is I will have my dimension description on the right side now with the sample_size being 24 I will have 2 dimensions linked to my sheet model this will change every time as well. Finally I want to put the reading in the rest of the table for each Inspection_val and dimension- so if I have 2 dimensions with a sample_size of 24 I should have 48 Inspeciton_vals with that I want to use the correct reading for the coresponding dimension and serial number. Here is what I have so far--
<div class="container">
<div class="row">
<div>
<table >
<thead>
<tr>
<th>Serial Number</th>
{% for ss in sample_size %}
<th>{{ ss.serial_number }}</th>
{% endfor %}
</tr>
<tr>
{% for r_c in complete_data %}
<th> {{ r_c.reading }} </th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for desc in dim_description.all %}
<tr>
<th> {{ desc }}</th>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
Here is what it looks like now
Here is what I would like it to look like
Bonus here is what my data looks like
Fix after answer suggestions still not displaying it how I would like it to..
<div class="container">
<div class="row">
<div>
<table >
<thead>
<tr>
<th>Serial Number</th>
{% for ss in sample_size %}
<th>{{ ss.serial_number }}</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for desc in dim_description.all %}
<tr>
<td> {{ desc }}</td>
</tr>
{% for r_c in complete_data %}
<td> {{ r_c.reading }} </td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
Picture of what it looks like now
Updated code with #Michael Platt suggestion
<div class="container">
<div class="row">
<div>
<table >
<thead>
<tr>
<th>Serial Number</th>
{% for ss in sample_size %}
<th>{{ ss.serial_number }}</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for desc in dim_description.all %}
<tr>
<td> {{ desc }}</td>
{% for r_c in complete_data %}
<td> {{ r_c.reading }} </td>
{% endfor %}
{% endfor %}
</tr>
</tbody>
</table>
</div>
</div>
</div>
#Michael Platt helped fix the html issue now I want to be able to split the reading in half so 24 will go on the inner od row and the next 24 will go on the outter od row.
Ok so knowing that I think this is your problem here:
<tbody>
{% for desc in dim_description.all %}
<tr>
<td> {{ desc }}</td>
{% for r_c in complete_data %}
<td> {{ r_c.reading }} </td>
{% endfor %}
{% endfor %}
</tr>
</tbody>
You had an extra <\tr> just before your second {% endfor %} in the <tbody> tags. I've changed it above so I think it will give the right design you want. If it doesn't let me know but it's a bit hard to test on my end just because I don't have the app up and running :-)
Cheers,