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()
2

1 Answer 1

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

1 Comment

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 :)

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.