Search code examples
pythondjangosqlitemodelinventory

SQLite Django Model for Inventory of Seeds


I'm trying to build an Inventory Model for a Django App that handles the sale of seeds. Seeds are stored and sold in packs of 3, 5, or 10 seeds of a single variety (for example: 3 pack of mustard seeds).

I want to add x amount of products to inventory with a price for each entry, and sell that product at that price for as long as that entry has items left(quantity field > 0) even if later entries have been made for the same product and presentation but at a different price, so i have the following model:

class Product(models.Model):
    name = models.CharField(max_length=100)

class Presentation(models.Model):
    seed_qty = models.IntegerField()

class Stock(models.Model):
    date = models.DateField(auto_now=True)
    quantity = models.IntegerField()
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    presentation = models.ForeignKey(Presentation, on_delete=models.CASCADE)
    cost = models.FloatField(null=True, blank=True)
    sell_price = models.FloatField(null=True, blank=True)

I'm wondering if I should actually relate Product and Stock with a ManyToMany field through a GeneralEntry intermediate model in which I'd store date_added, presentation and cost/price.

My issue is that when I add multiple Stock entries for the same product and presentation, I can't seem to query the earliest prices for each available (quantity>0) stock entry for each product.

What I've tried so far has been:

stock = Stock.objects.filter(quantity__gt=0).order_by('-date')
stock = stock.annotate(min_date=Min('date')).filter(date=min_date)

But that returns that max_date isn't defined.

Any ideas on how to query or rearrange this model ?

Thanks!

*** UPDATE : I wasn't using F() function from django.db.models.

Doing it like this works:

stock = Stock.objects.filter(quantity__gt=0).order_by('-date')
stock = stock.annotate(min_date=Min('date')).filter(date=F('min_date'))

Solution

  • Turns out I wasn't using F() function from django.db.models.

    Doing it like this works:

    stock = Stock.objects.filter(quantity__gt=0).order_by('-date')
    stock = stock.annotate(min_date=Min('date')).filter(date=F('min_date'))