I aim to create a dataframe of the Top 3 Selling menu_items in my Purchases table. My thoughts are to create a join on the Purchases
model with the Menu_Item
model where Purchases.menu_item = Menu_Item.title
. I will convert the QuerySet to a DataFrame using django_pandas.io
. I plan to use the sum of Menu_Item.price
associated with each distinct Purchases.menu_item
to determine the Top 3 menu_items of all the instances in the Purchases model
. My problem is that I cannot join the two models successfully. I’ve scoured the interwebz for a working solution to join two models with different field names, which returns all instances, and I tried various solutions, but the scarce articles on this topic yielded no joy.
models.py
...
class MenuItem(models.Model):
title = models.CharField(max_length=200, unique=True)
price = models.FloatField(default=0.00)
def get_absolute_url(self):
return "/menu"
def available(self):
return all(X.enough() for X in self.reciperequirement_set.all())
def __str__(self):
return f"title={self.title}; price={self.price}"
class Purchase(models.Model):
menu_item = models.ForeignKey(MenuItem, on_delete=models.CASCADE)
timestamp = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f"menu_item=[{self.menu_item.__str__()}]; time={self.timestamp}"
def get_absolute_url(self):
return "/purchases"
I am trying to access and convert the data with:
>>> from django_pandas.io import read_frame
>>> from django.db.models import F
purchases = Purchase.objects.values(
'timestamp',
item_title=F('menu_item__title'),
item_price=F('menu_item__price'),
item_desc=F('menu_item__description'))
df = read_frame(purchases)
The results are:
>>> df
timestamp item_title item_price item_desc
0 2022-10-09 22:52:56.159353+00:00 Django Djaffa Cake 8.25 Djaffa cakes are circular and have three layers...
>>>
This is the same result as when I do the process with just a single model, the Purchase
model:
>>> query = Purchase.objects.all()
>>> df = read_frame(query)
>>> df
id menu_item timestamp
0 1 title=Django Djaffa Cake; price=8.25 2022-10-09 22:52:56.159353+00:00
As it turns out, menu_item
Django Djaffa Cake is the last instance of a Menu_Item,
and not a menu_item
referenced in the Purchase
model. There are currently no purchases of Django Djaffa Cake. I cannot figure out why it is showing up here. I once had an instance but it was deleted.
My problem is not just in the join but the basic query? Or perhaps there is something going wrong when the dataframe is created. Being a rookie at this, I can’t tell. Elsewhere in my code, I use purchase.menu_item.reciperequirement_set.all()
to join two models successfully, where they have the same column name and return all instances.
Your help with this would be gratefully appreciated.