Home > Enterprise >  how to do less than django queryset with column parameter
how to do less than django queryset with column parameter

Time:11-29

I want to count my stock as this sql code:

SELECT COUNT(*) FROM management_stock
WHERE stockCount < minStock

How to do that query in django queryset? I got error in my this query:

Stock.objects.all().filter(stockCount__lt=minStock).count()

my table is like this:

class Stock(models.Model):
    product = models.OneToOneField(Product, on_delete=models.CASCADE)
    bengkel = models.OneToOneField(Bengkel, on_delete=models.CASCADE)
    stockCount = models.PositiveIntegerField()
    minStock = models.PositiveIntegerField()

I tried that code then my eror is : NameError: name 'minStock' is not defined.

CodePudding user response:

You can use an F-expression [Django-doc] to reference a field, so:

from django.db.models import F

Stock.objects.filter(stockCount__lt=F('minStock')).count()
  • Related