Reputation: 3733
I define a variable in a view like so:
{{import datetime}}
{{top10 = db( db.table.date > datetime.datetime.now() ).select()[:10]}}
and then go on to use that variable.
As this is in a view I want to extend I'd rather not define that variable in a controller and then pass it through, which is why I implemented as I did.
I also don't like that I'm importing something in a view.
Is there an alternative to (a) importing in a view (b) defining a variable in a view? If this is good practice I'm happy to keep it.
Thank you!
Upvotes: 2
Views: 174
Reputation: 25536
Anything you add to the environment in a model file will be available in the view, so you could include the import statement in any model file. However, I don't think there is any good reason not to do the import in the view, which may make more sense given that the module is actually being used there (and not in the model file).
If your goal is to minimize the logic in the view, then a better approach might be to move both lines into a model file (you can use conditional models if you only need the top10
variable for particular controllers/functions).
Also, in this case, you really don't need the datetime
module, as you can use request.now
in place of datetime.datetime.now()
(the only difference is that request.now
will have been calculated a few milliseconds earlier, as its value is populated by the framework at the start of the request).
Also, you can make your database query more efficient by using limitby
to limit the select to the first 10 records, rather than selecting all matching records and then using Python to extract the first 10:
top10 = db(db.table.date > request.now).select(limitby=(0, 10))
Finally, if the top 10 records don't change frequently, you might consider caching the select.
Upvotes: 3