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.

1

2 Answers 2

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']
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.