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}
Keshav Agarwal
  • 811
  • 1
  • 10
  • 28
  • If you have two identical models may be something wrong with your database schema, and you should move your model name into tables field. – Yevgeniy Shchemelev Jan 10 '16 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. – Keshav Agarwal Jan 10 '16 at 12:08

3 Answers3

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.

RodrigoDela
  • 1,706
  • 12
  • 26
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)
andreas-hofmann
  • 2,378
  • 11
  • 15
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)
Amiay Narayan
  • 461
  • 9
  • 8