Select random row from datatable subset and show output

Hi all,

New to Anvil, and so far it rocks! however, i’m stuck and could use some help.

I’ve created a datatable with recipes (title, URL, type (dinner or lunch), ingredients, etc.). Now i want to create an application which has a button and when you press the button a random recipe will be shown.

Now for where i’m stuck at: I’ve managed to show the title of a recipe as well as the image when a button is pressed, however i would like to do this on a random row in my datatable.

So, first select a subset of recipes (all dinner recipes) then select a random row from this subset. and then finally show the image and title.

Code:

  def button_1_click(self, **event_args):
    dinner_recipes = app_tables.recipe.search(Type = "Diner")
    single_row = app_tables.recipe.search(Title="3x gepofte zoete aardappel")

    title = [r['Title'] for r in single_row]
    image_url = [r['Picture_url'] for r in single_row]
    
    self.label_2.text= title[0]
    self.image_1.source=image_url[0]

The single_row part is now just a recipe i choose myself. this i would like to be random. Anyone that can offer any help?

hi @Lars.van.midden and welcome to the forum

you can use the random module on the client and the server

what about something like

from random import randint
dinner_recipes = app_tables.recipe.search(Type="Dinner")
rand_idx = randint(0, len(dinner_recipes) - 1)
rand_recipe = diner_recipes[rand_idx]

worth noting that it would probably be beneficial for performance to move these calls to the server when you’re ready

like

def button_1_click(self, **event_args):
   rand_recipe = anvil.server.call('get_random_recipe')
2 Likes

Hi @stucork,

It worked perfectly! Thank you very much!