3

I have two identical models, let's say X and Y in django like this:

class X(models.Model):
    con = models.CharField(max_length=100)
    a = models.ForeignField("FOO")

class Y(models.Model):
    con = models.CharField(max_length=100)
    b = models.ForeignField("BAR")

To access an object of these models, I have to use the following code:

models.X.objects.get(
    con = "something",
    a = xy
)

models.Y.objects.get(
    con = "something",
    b = yx
)

Is there a way to set the model name as variable such as model_name = X and then use this code to access the objects:

models.model_name.objects.get(**my_dict)

where

my_dict = {"con":"something", "a":xy}
2
  • If you have two identical models may be something wrong with your database schema, and you should move your model name into tables field. Commented Jan 10, 2016 at 11:59
  • The app requires two models because I need two different foreign keys coupled with other fields which are similar but may contain different values. Commented Jan 10, 2016 at 12:08

3 Answers 3

5

You could do something like this:

getattr(models, model_name).objects.get(**my_dict)

It allows you to access the attributes of models via strings or variables.

Sign up to request clarification or add additional context in comments.

2 Comments

so basically, what I should do is getattr(models, X).objects.get(**my_dict)?
No, X should be written as string. So you write getattr(models, 'X').objects.get(**my_dict)
3

You certainly can:

setattr(models, 'model_name', models.X)

This will set the model_name attribute to models.X (or models.Y), which will make your call models.model_name.objects.get(**my_dict) succeed.

Alternatively, you could save the model you want to use in a variable before doing your work and use that from then on:

model_name = models.X
model_name.objects.get(**my_dict)

Comments

0

Another way that I used is to use django.apps:

from django.apps import apps
model_name = 'X' # or 'Y'
my_dict = {"con":"something", "a":xy} # as suggested in the problem

model_class = apps.get_model(
  app_label='name_of_app_where_model_is_defined', 
  model_name=model_name
)
model_class.objects.get(**my_dict)

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.