1

In my project, I want to be able to create a list of Querysets, where each Queryset is named after the category of their respective items. I am familiar with dynamically naming variables in the context of system paths/directories (where I use f'{}), but I'm unsure how to utilize any aspect of this in my current problem. I intended for my function to look something like this:

def productsfromcategory(categories):
   productcontext = []
   for category in categories:
      {dynamicallynamedvariable} = Product.objects.prefetch_related("product_image").filter(category=category)[15]
      print(dynamicallynamedvariable)
      biglist.append(dynamicallynamedvariable)

In this, I meant for dynamicallynamedvariable to be the name of the current category being looped through but I'm unsure as to how to implement this. Any advice on how to tackle this problem would be much appreciated.

bimmui
  • 131
  • 1
  • 11
  • 1
    Does this answer your question? [How do I create variable variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables) – Abdul Aziz Barkat Jun 21 '21 at 17:07

2 Answers2

1

Example with usage of globals under the sample data:

def productsfromcategory(categories):
   productcontext = []
   for category in categories:
      globals()[category] = category
      print(globals()[category])
      productcontext.append(globals()[category])
   return productcontext
      
productsfromcategory(["a", "b"])
# a
# b
# ['a', 'b']
polkas
  • 3,797
  • 1
  • 12
  • 25
0

The outlined problem deserves to be solved by using dict data structure.

Dict documentation

This will alow You to store key, value pairs where key can be string allowing for the described functionality.

Sample code based on what You have shared:

def productsfromcategory(categories):
   productcontext = {}
   for category in categories:
      productcontext[category] = Product.objects.prefetch_related("product_image").filter(category=category)[15]

Such implementation will result in:

{"category_0": assigned_value_0, "category_1": assigned_value_1}

If You need any further assistance please provide more detail.

Kaszanas
  • 446
  • 4
  • 18