Distinguishing parent model's children with Django inheritance

后端 未结 3 2124
臣服心动
臣服心动 2021-01-24 06:12

Basically I have a Base class called \"Program\". I then have more specific program model types that use Program as a base class. For 99% of my needs, I don\'t care whether or n

3条回答
  •  误落风尘
    2021-01-24 06:34

    // Update

    As pointed out in the comments to this post I got the question wrong. The answer below will not solve the problem.


    Hi f4nt,

    the easiest way I can think of right now would be the following:

    program = models.Program.objects.get(id=15)
    
    if program.__class__.__name__ == 'ModelA':
      # to something
    
    if program.__class__.__name__ == 'ModelB':
      # to something
    

    To make this a bit better you could write a method in the base model:

    class MyModel(models.Model):
    
      def instanceOfModel(self, model_name):
        return self.__class__.__name__ == model_name
    

    That way the code from above would look like this:

    program = models.Program.objects.get(id=15)
    
    if program.instanceOfModel('ModelA'):
      # to something
    
    if program.instanceOfModel('ModelB'):
      # to something
    

    But as you can imagine this is ugly. You could look into the content type framework which might help you to do the same except more elegent.

    Hope that helps!

提交回复
热议问题