0

In django I want to call a queryset but the name of that queryset will vary depending on what variable is being passed to it.

In this example I have a variable called var that will return a value of "fileone", "filetwo" or "filethree"

how do I then use that to create the appropriate queryset to be called?

ie.

var = filetwo

queryset = filetwo.objects.all()

var = fileone

queryset = fileone.objects.all()
karthikr
  • 97,368
  • 26
  • 197
  • 188
whoisearth
  • 4,080
  • 13
  • 62
  • 130
  • 2
    Use an appropriate data structure such as a ``dict``. – James Mills Jul 03 '14 at 03:52
  • possible duplicate of [Make a list with a name that is only known after the program runs](http://stackoverflow.com/questions/16092341/make-a-list-with-a-name-that-is-only-known-after-the-program-runs) – Zero Piraeus Jul 03 '14 at 03:56

1 Answers1

3

Approach (1), If you can assign Class to variable In Python you can directly assign a Class to a variable. If your variable holds the class you can directly call it. This is how I do it -

The model -

class ErrorLog(models.Model):

    class Meta:
        app_label = 'core'

The url config, passing Model Class in variable -

url(r'^' ..., GenericListView.as_view(..., model=ErrorLog,...), name='manage_error'),

Then finally calling the query set in the view -

class GenericListView(...):
    model = ....
    def get_queryset(self):
        //other codes
        return self.model.objects.all()

You see the query_set will return whatever class mentioned in it.

Approach (2), if you only has the class name But in case, your variable only contains string name of the 'Class but not the class directly then you might wanna get the model before calling the queryset -

to get the model class you can do the following -

from django.db.models import get_model
model = get_model("string name of model class")
return model.objects.all()
brainless coder
  • 6,310
  • 1
  • 20
  • 36
  • Thanks this was exactly what I was looking for! I've just started building my views as class based to use the mixins for django-rest-framework so this is all making sense now :) – whoisearth Jul 04 '14 at 03:09