Django : querying data from related models - python

I use Django 3.2.7 and I would like to query all orders from a customer.
Models.py
class Order(models.Model):
STATUS=(
('Pending','Pending'),
('Out for Delivery','Out for delivery'),
('Delivered','Delivered'),
)
customer = models.ForeignKey(Customer,null=True, on_delete=models.SET_NULL)
product = models.ForeignKey(Product,null=True, on_delete=models.SET_NULL)
date_created = models.DateTimeField(auto_now_add=True)
status = models.CharField(max_length=200, null=True, choices=STATUS)
Views.py
def customer(request,pk):
customer = Customer.objects.get(id=pk)
orders = customer.order_set.all()
my_context={
'customer':customer,
'orders':orders
}
return render(request, 'accounts/customer.html', context=my_context)
Urls.py
path('customer/<str:pk>/', views.customer),
Template
{% for order in orders %}
<tr>
<td>
{order.product}
</td>
<td>
{order.product.category}
</td>
<td>
{order.date_created}
</td>
<td>
{order.status}
</td>
<td>Update</td>
<td>Delete</td>
</tr>
{% endfor %}
My problem is that instead of printing the actual data on the template is prints the query data.
I think the problem is at
orders = customer.order_set.all()
What am I doing wrong?

Related

Django Join two models

I'm beginner to Django. I want to ask how can I get the addresses of all the Dials that are in DataUpload table from BO table. It doesn't return any data in Customer_Address column in HTML.
class DataUpload(models.Model):
Dial = models.IntegerField()
Customer_Address = models.ForeignKey(BO, on_delete=models.CASCADE,
null=True,blank=True, related_name='address')
National_ID = models.IntegerField()
Customer_ID = models.IntegerField()
Status = models.CharField(max_length=100)
Registration_Date = models.DateTimeField(max_length=100)
Is_Documented = models.CharField(max_length=100, null=True)
BO Model:
class BO(models.Model):
id = models.AutoField(primary_key=True)
Dial = models.IntegerField()
Customer_Address = models.CharField(max_length=100, null=True, blank=True)
Wallet_Limit_profile = models.CharField(max_length=100, null=True, blank=True)
View:
def listing(request):
data = DataUpload.objects.all()
paginator = Paginator(data, 10) # Show 25 contacts per page.
page_number = request.GET.get('page')
paged_listing = paginator.get_page(page_number)
# print(data)
return render(request, 'pages/listing.html', {'paged_listing': paged_listing, 'range': range})
When I call item.Customer_Address it does return any data and no errors are appearing, also I tried item.Customer_Address_id.Customer_Address same thing.
HTML:
{% for item in paged_listing %}
<tr>
<td class="text-center align-middle">{{ item.Dial }}</td>
<td class="text-center align-middle">{{ item.Customer_Address}}</td>
<td class="text-center align-middle">{{ item.National_ID }}</td>
<td class="text-center align-middle">{{ item.Status }}</td>-->
<!-- <td>Edit </td> -->
<td class="text-center align-middle"> <button class="btn btn-primary"><a class="edit-link"
href="{% url 'edit_record' item.id %}">Edit</button> </a> </td>
</tr>
{% endfor %}

how to call property method from model class to html in django

Im making a django app, and its basically an admin site, i have an app called calculator, inisde it i have 3 models Transaction, FamilyGroup and FamilyMember, each model has some property methods for calculation purposes. here are the models for more clearness :
class Transaction(models.Model):
chp_reference = models.CharField(max_length=50, unique=True)
rent_effective_date = models.DateField(null=True, blank=True)
income_period = models.CharField(max_length=11)
property_market_rent = models.DecimalField(max_digits=7)
#property
def ftb_combined(self):
ftb_combined = 0
for family_group in self.familygroup_set.all():
ftb_combined += family_group.ftb_combined
return ftb_combined
class FamilyGroup(models.Model):
name = models.CharField(max_length=10)
transaction = models.ForeignKey(Transaction, on_delete=models.CASCADE)
last_rent = models.DecimalField(max_digits=7)
#property
def additional_child_combined(self):
return (self.number_of_additional_children
or 0) * self.maintenance_rate_additional_child
class FamilyMember(models.Model):
transaction = models.ForeignKey(Transaction, on_delete=models.CASCADE)
family_group = models.ForeignKey(FamilyGroup, on_delete=models.CASCADE, null=True, blank=True)
name = models.CharField(max_length=100, null=True, blank=True)
date_of_birth = models.DateField(null=True, blank=True)
income = models.DecimalField(max_digits=6)
#property
def weekly_income(self):
if self.transaction.income_period == 'Weekly':
return self.income
return (self.income or 0) / 2
this is how my models are connected, now i made a method in views.py as below:
def transaction_print(request, transaction_id):
transaction = Transaction.objects.get(id=transaction_id)
return render(request, 'report.html', {'transaction':transaction})
I want to make a report in report.html, 1 report for each transaction, and the transaction can have many FamilyGroups and FamilyMember, and will include almost all the data from the models and the property methods inside it.
here what i thought in the report.html
<table class="table">
<thead class="thead-dark">
<tr>
<th>CHP Reference </th>
<th>Rent Effective From (dd/mm/yyyy)</th>
<th>CRA Fortnightly Rates valid for 6 months from</th>
<th>Market Rent of the Property </th>
<th>Number of Family Groups </th>
</tr>
</thead>
<tbody>
<tr>
<td>{{ transaction.chp_reference }} </td>
<td>{{ transaction.rent_effective_date }} </td>
<td>0</td>
<td>{{ transaction.property_market_rent }}</td>
<td>{{ transaction.number_of_family_group }}</td>
</tr>
</tbody>
{% for family_group in transaction.family_group_set.all %} ??
{% for m in family_group.transaction.family_group_set.all %} ??
</table>
Im really not sure how to perform the nested loop to iterate through the FamilyGroup and FamilyMember inside the transaction report.html would appreciate a hint how this be done.
According to the documentation Django sets the name to MODELNAME_set. However you can still use the related_name property to set a name for your backward reference (you will still be able to use MODELNAME_set as well).
Here's how to achieve it using related_name:
models.py
class FamilyGroup(models.Model):
name = models.CharField(max_length=10)
transaction = models.ForeignKey(Transaction, on_delete=models.CASCADE, related_name="family_groups") # Notice the related_name here as it will be used later on
last_rent = models.DecimalField(max_digits=7)
# ...
class FamilyMember(models.Model):
transaction = models.ForeignKey(Transaction, on_delete=models.CASCADE, related_name="family_members") # Notice the related_name
family_group = models.ForeignKey(FamilyGroup, on_delete=models.CASCADE, null=True, blank=True)
name = models.CharField(max_length=100, null=True, blank=True)
date_of_birth = models.DateField(null=True, blank=True)
income = models.DecimalField(max_digits=6)
# ...
Now you can loop through them like so:
report.html
{% for family_group in transaction.family_groups.all %}
{{ family_group.name }}
{% endfor %}
{% for family_member in transaction.family_members.all %}
{{ family_member.name }}
{% endfor %}

How to properly make a query in Django?

I've ran into a little problem. I want to construct a proper queryset to get values which represent the number of the expenses per category to display this like that.
This is what I got now:
class CategoryListView(ListView):
model = Category
paginate_by = 5
def get_context_data(self, *, category_object_list=None, **kwargs):
**categories = Category.objects.annotate(Count('expense'))
queryset = categories.values('expense__count')**
return super().get_context_data(
category_object_list=queryset,
**kwargs)
Of course it doesnt work and I have terrible table like this. I suppose the problem isn't in HTML but in my absolutely wrong query... What should I do?
This is my HTML in case it would be needed:
{% for category in object_list %}
<tr>
<td>
{{ category.name|default:"-" }}
</td>
<td>
{% for number in category_object_list %}
{{ number.expense__count }}
{% endfor %}
</td>
<td>
edit
delete
</td>
{% endfor %}
</tr>
Also my models.py:
class Category(models.Model):
name = models.CharField(max_length=50, unique=True)
def __str__(self):
return f'{self.name}'
class Expense(models.Model):
class Meta:
ordering = ('-date', '-pk')
category = models.ForeignKey(Category, null=True, blank=True,
on_delete=models.CASCADE)
name = models.CharField(max_length=50)
amount = models.DecimalField(max_digits=8, decimal_places=2)
date = models.DateField(default=datetime.date.today, db_index=True)
def __str__(self):
return f'{self.date} {self.name} {self.amount}'
You can try like this within your template with the reverse look up of
Foregin Keys. See the docs for more detail.
{% for category in object_list %}
<tr>
<td>
{{ category.name|default:"-" }}
</td>
<td>
{{category.expense_set.all.count}}
</td>
<td>
edit
delete
</td>
{% endfor %}
</tr>
Now in the view you can just pass all the categories with the ListView
class CategoryListView(ListView):
model = Category
paginate_by = 5

Django: Sum Total value over Foreign Key Data

I am using Django 1.11 and Python3.5
I have created a table. This is a screenshot.
When I got a table from my query database, it is showing 10+2+3... but I want to get total sum value for every customer within Due Taka update column in table like this 10+2+4+2 = 18
this is my model.py file
class CustomerInfo(models.Model):
customer_name = models.CharField('Customer Name', max_length=100)
customer_mobile_no = models.CharField(
'Mobile No', null=True, blank=True, max_length=12)
customer_price=models.IntegerField('Customer Price',default=1)
customer_product_warrenty = models.CharField('Product Warrenty',null=True, blank=True,max_length=10)
customer_sell_date = models.DateTimeField('date-published', auto_now_add=True)
customer_product_id=models.CharField('Product ID',max_length=300,null=True, blank=True)
customer_product_name=models.TextField('Product Name')
customer_product_quantity=models.IntegerField('Quantity',default=1)
customer_uid = models.CharField(max_length=6, blank=True, null=True)
customer_info=models.TextField('Customer Details Informations', blank=True, null=True)
customer_conditions=models.CharField('Conditions',blank=True, null=True, max_length=300)
customer_due_taka_info=models.IntegerField(default=0)
customer_discount_taka=models.IntegerField(default=0)
customer_first_time_payment=models.IntegerField('First Time Payment',default=0)
customer_first_due_info = models.CharField('First Due Info',default='No due info', max_length=200, blank=True, null=True)
customer_product_mrp=models.IntegerField('Products MRP', default=0)
customers_refrence=models.CharField(max_length=100)
customer_updated = models.DateTimeField(auto_now=True)
customer_type=models.CharField('Customer Type', default='MobilePhone', max_length=50)
def __str__(self):
return self.customer_name
def remainBalance(self):
if self.customer_price > self.customer_due_taka_info:
remain=self.customer_price - self.customer_due_taka_info
return remain
def totalRetalsPerSingle(self):
return self.customer_product_quantity * self.customer_product_mrp
#def product_warrenty(self):
#expire_date_oneyr =self.customer_sell_date+ datetime.timedelta(days=365)
#return 'This product expire on this date ' + str(expire_date_oneyr)
class Meta:
verbose_name = ("গ্রাহকের তথ্য")
verbose_name_plural = ("গ্রাহকের তথ্যসমূহ")
#intregated with Customerinfo Model (Using foreignKey)
class DueTaka(models.Model):
customer_due = models.IntegerField('Due Taka', default=0)
customer_due_date=models.DateTimeField(auto_now_add=True)
customer_due_info=models.CharField('Due Info', max_length=200, blank=True, null=True)
customerinfo = models.ForeignKey(CustomerInfo, on_delete=models.CASCADE)
due_customer_updated = models.DateTimeField(auto_now=True)
def __int__(self):
return self.customer_due
def sum_total(self):
return self.customer_due
this is my views.py file
due_update_info = CustomerInfo.objects.filter(duetaka__customer_due_date__range=(starts_date, tomorrow)).order_by('-customer_updated')
I want to get total price customer_due fields within DueTaka model for per single customer. if a customer name is 'asad'. He has some multple due taka and he paid multiple times like this 10+20+20 Now I want to get total value like 50
If I update my customer's profile, same customers name come again with in loop my table. But I don't want this.
and this is my html template file
<h1>Due Paid Book</h1>
<table class="table table-hover table-bordered">
<p style="font-size:16px;">Due Paid Tody</p>
<thead>
<tr>
<th>No</th>
<th>Name</th>
<th>Invoice ID</th>
<th>Mobile</th>
<th>Product</th>
<th>Product MRP</th>
<th>Customer Paid (TK)</th>
<th>Due Amount</th>
<th>Total Price</th>
<th>Warrenty</th>
<th>Purchase Date</th>
<th>Due Taka update</th>
<th>Update Date</th>
<th>QN</th>
</tr>
</thead>
{% for x in due_update_info %}
<tbody>
<tr>
.......code in here.......
<td>
{% for y in x.duetaka_set.all %}
{{y.customer_due | intcomma}}+
{% endfor %}
{{x.duetaka_set }}
<!--i want to toatal value in here, now nothing showing-->
{{total_price}}
</td>
</tr>
<tr>
</tr>
</tbody>
{% endfor %}
<td colspan="10"></td>
<td> Total Du Paid <br> <i>{{starts_date}} to {{end_date}}</i> </td>
<td> <b>{{dupaid_today|intcomma}} TK</b> </td>
</table>
Now How can I implement in views file?
Maybe change the filter query like this this:
CustomerInfo.objects.filter(duetaka__customer_due_date__range=(starts_date, tomorrow)).annotate(due_taka_total=Sum('duetaka__customer_due')).order_by('-customer_updated')
which will give you additional field 'due_taka_total', which can be used in template, like:
{{ y.due_taka_total }}
assuming y is an object of CustomerInfo
OR
You could write a custom template tag and find out the total using it:
from django import template
register = template.Library()
#register.simple_tag
def get_total_taka(customer_info_object):
return sum([each.customer_due for each in customer_info_object.duetaka_set.all()])
and use it in template like this:
{% get_total_taka y %}
assuming y is an object of Customerinfo
For writing the custom template tag refer: Writing Custom Tags

Django prefetch_related outputs None

I'm new to Django. I am making a simple store.
Currently I am working on the Order section.
Every Order has Order Items inside it. Every order item has some values and a product id.
What I am trying to display on the index.html, is the orders and its items inside it. However order.items always outputs order.OrderItem.None
views.py
class IndexView(generic.ListView):
template_name = 'order/index.html'
context_object_name = 'all_orders'
def get_queryset(self):
return Order.objects.all().prefetch_related('items')
def get_context_data(self, **kwargs):
context = super(IndexView, self).get_context_data(**kwargs)
return context
views.py
# Create your models here.
class Order(models.Model):
user = models.ForeignKey(User, related_name='orders')
created_at = models.DateTimeField(auto_now_add=True, null=True)
class OrderItem(models.Model):
product = models.ForeignKey(Product)
order = models.ForeignKey(Order, related_name='items')
item_name = models.CharField(max_length=255, null=True, blank=True)
item_price_in_usd = models.DecimalField(max_digits=6, decimal_places=2, null=True, blank=True)
def __str__(self):
return self.product.name
index.html
{% for order in all_orders %}
<tr>
<td>{{ order}}</td>
<td>{{ order.created_at}}</td>
<td>{{ order.items}}</td>
</tr>
{% endfor %}
Ok, I have found to solution. Apparently you have to add .all
{% for order in all_orders %}
<tr>
<td>{{ order}}</td>
<td>{{ order.created_at}}</td>
<td>
{% for items in order.items.all %}
<td>{{ items.item_name}}</td>
{% endfor %}
</td>
</tr>
{% endfor %}

Categories