bharal
bharal

Reputation: 16214

django can i store the type of a model in a variable for use in a method call?

i'm not sure what terms python uses for objects - forgive my lack of python know how!

Effectively, how can i do this:

strToObject = {'story':Story,'post':Post}

def post(self,request):
    type = request.POST['theTypeInTheForm']
    id = request.POST['idInTheForm']
    get_object_or_404(strToObject.get(type,None),id)

so what this is doing is taking a value from a form field, working out what type we're talking about, and then pulling from the db the right type from the id.

I don't quite know how to do this though. (the form is really for a rating button, so i don't really have a whole form behind it!)

Upvotes: 0

Views: 62

Answers (2)

Chris Pratt
Chris Pratt

Reputation: 239440

First, you need to be more careful getting the model from strToObject. As it stands, if type is not one of "story" or "post", get_object_or_404 will be fed None as the model, and your code will blow up. Do something like this instead:

model = strToObject.get(type) # `None` is the "default" default
if model is not None:
    get_object_or_404(model, id=id)

Second, as I indicated in the above code, you can't just pass the id as is to get_object_or_404, you need to specify what field on the model the value should be looked up on, hence id=id.

Third, you should be using get on request.POST to get the type and the id. As it is now, if they're not in the form for whatever reason, your code will blow up with an IndexError:

type = request.POST.get('theTypeInTheForm')
id = request.POST.get('idInTheForm')

Then, you should check that the values are not None before proceeding:

if type is not None and id is not None:
    # the rest of your code

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 600041

You probably want to use ContentTypes, which is a model containing all the different models defined in your app.

Upvotes: 2

Related Questions