André Abboud
André Abboud

Reputation: 2030

django get to know what submodel is associated to the main model

I have a model called Animal and there are multiple models that have Animal as OneToOneField

class Animal(models.Model):
    name = models.CharField(max_length=20)
    description = models.TextField()

class Cat(models.Model):
    animal = models.OneToOneField(Animal, on_delete=models.CASCADE)
    name = models.CharField(max_length=20)

class Dog(models.Model):
    animal = models.OneToOneField(Animal, on_delete=models.CASCADE)
    name = models.CharField(max_length=20)

class Lion(models.Model):
    animal = models.OneToOneField(Animal, on_delete=models.CASCADE)
    name = models.CharField(max_length=20)

(nb . there are 50 submodels) Only When an ad is created , so it will associated to only one of 50 submodel car,boat or truck so after that i am creating a view to display the name of the Animal but how can i know what is the sub model associated to the ad to get the data from it to.

def get_ad_details(request, id):
    animal = Animal.objects.get(id=id)

    #need to call a method to get a boat or car or truck or .... that is associated to the ad so how?

Upvotes: 0

Views: 465

Answers (1)

ivissani
ivissani

Reputation: 2664

One possible way would be to use model inheritance and then use InheritanceManager from django-model-utils package.

If you do not want to do that you can take a look at its code for inspiration. Essentially you'd need to cycle throw every possible related field to see which one is set, so in your example it would be something like:

def get_ad_details(request, id):
    possible_related_models = ['car', 'boat', 'truck']
    ad = Ad.objects.get(id=id).select_related(possible_related_models)  # select_related prevents one query for each model afterwards

    #need to call a method to get a boat or car or truck or .... that is associated to the ad so how?
    relboject = None
    for relmodel in possible_related_models:
        relobject = getattr(ad, relmodel, None)
        if relobject:
            break

Upvotes: 1

Related Questions