2

In variable called object_type I store values like: Profile or Company which are names of models available in the app. Both models has field called uuid.

I need to something like this:

get_object_or_404(object_type, uuid=uuid_from_request)

how can I pass object_type value (Profile or Company) to query correct model?

2 Answers 2

3

How about using a dictionary that map model names to model classes:

object_types = {'Profile': Profile, 'Company': Compnay}

...

get_object_or_404(object_types[object_type], uuid=uuid_from_request)

Or using getattr:

import app.models

get_object_or_404(getattr(app.model, object_type), uuid=uuid_from_request)
Sign up to request clarification or add additional context in comments.

2 Comments

About first option: type is stored in another object attribute. I am not sure how to use in my case.
@dease, What another object?
1

In django all model types are stored in magical cache, so you might use this cache to get model types, like that:

 from django.db.models.loading import get_model
 Model = get_model("your_app_name", "Profile")
 get_object_or_404(object_type, uuid=uuid_from_request)

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.