I have a function ‘is_recently’ that checks how long the item I added has been hanging, and if 30 minutes have not passed yet, then write that it is recently on sale. I decided to optimize queries in the database, and I cannot add this function to the parameters of the values function, is it possible to do this at all? Forgive me in advance if I wrote with errors, I’m not English speaking.
def index(request):
data = (
Product
.objects.select_related('category')
.filter(is_on_main=True)
.values('name','price','pk','date')
)
Maybe there are some other functions? Or I don’t understand something
>Solution :
No tat is not possible, since this is a property, and not a field. But using .values(…) [Django-doc] is often bad code design: it introduces a primitive obsession code smell [coding-guru].
Likely it is better to work with .only(…) [Django-doc], since that will still create model objects, but only load a subset of the fields. In case other fields are necessary, it will make extra queries:
def index(request):
data = (
Product.objects.select_related('category')
.filter(is_on_main=True)
.only('name', 'price', 'pk', 'date')
)