Distinguishing parent model's children with Django inheritance

后端 未结 3 2092
臣服心动
臣服心动 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:39

    Have you tried hasattr()? Something like this:

    if hasattr(program, 'swimprogram'):
        # ...
    elif hasattr(program, 'campprogram'):
        # ...
    

    If you are unsure about this approach, try it out in a simple test app first. Here are two simple models that should show if it will work for you and the version of django that you are using (tested in django-1.1.1).

    class Archive(models.Model):
        pub_date = models.DateField()
    
        def __unicode__(self):
            return "Archive: %s" % self.pub_date
    
    class ArchiveB(Archive):
        def __unicode__(self):
            return "ArchiveB: %s" % self.pub_date
    

    And then giving it a spin in the shell:

    > a_id = Archive.objects.create(pub_date="2010-10-10").id
    > b_id = ArchiveB.objects.create(pub_date="2011-11-11").id
    > a = Archive.objects.get(id=a_id)
    > b = Archive.objects.get(id=b_id)
    > (a, b) # they both look like archive objects
    (, )
    > hasattr(a, 'archiveb')
    False
    > hasattr(b, 'archiveb') # but only one has access to an ArchiveB
    True
    

提交回复
热议问题