i have price model
class Product(models.Model):
price = models.IntegerField
membership_discount = models.DecimalField
if i get price parameter, (ex. min_price = 100000, max_price = 500000)
I want to get the products multiplied by the price fields and membership_discount fields.
not this
Product.objects.filter(price__range = (min_price, max_price))
i want
Product.objects.filter(price * (1 membership_discount)__range = (min_price, max_price))
CodePudding user response:
lte
= less than or equal to
gte
= greater than or equal to
this is documentation: https://docs.djangoproject.com/en/4.0/ref/models/querysets/#gt
max_price = #max price logic here
min_price = #min price logic her
#this will filter all products (price <= max_price and price >= min_price)
Product.objects.filter(price__lte = max_price, price__gte = min_price)
CodePudding user response:
You could use annotations for the QuerySet and apply the filter on the annotation.
Product.objects.annotate(
member_price=F('price') * (1 F('membership_discount'))
).filter(
member_price__range=(min_price, max_price)
)
If the price
field and the membership_dicsount
do not have the same type, you might need to make usage of the ExpressionWrapper
with a specific output_field
Product.objects.annotate(
member_price=ExpressionWrapper(
F('price') * (1 F('membership_discount')),
output_field=DecimalField()
)
).filter(
member_price__range=(min_price, max_price)
)
Docs: