简体   繁体   中英

Access Django SubClass Method from SuperClass

Okay, so I have two Django models:

class Ticket(BaseModel):
  name = models.CharField(max_length=200)
  description = models.TextField(blank=True, null=True)

  def get_absolute_url(self):
    return '/core/group/ticket/{0}/'.format(self.id)

class ProjectTicket(Ticket):
    project = models.ForeignKey('Project', on_delete=models.DO_NOTHING)
    phase = models.ForeignKey('ProjectPhase', blank=True, null=True, on_delete=models.DO_NOTHING)

    def get_absolute_url(self):
        return '/different/url/structure'

Now, I'm querying all Ticket objects with Ticket.objects.all(). This will return all Ticket objects, including some that are ProjectTicket subclasses.

What I'd like to be able to do is access the subclass get_absolute_url() when the objects in question are actual subclassed ProjecTicket objects.

I know that I can get the parent class from the subclass, but I want to be able to do the reverse.

Has anyone achieved something like this? If so, what approach did you take?

Here's one way that I can think of right now:

I'm sure you know that inheriting django models creates a OneToOne relationship with the parent. So, the Ticket objects which are also instances of ProjectTicket class, will have an attribute called projectticket on them. You can check for this value and return the url accordingly:

class Ticket(...):
    ...
    def get_absolute_url(self):
        if hasattr(self, 'projectticket'):
            return self.projectticket.get_absolute_url()
        else:
            return '/core/group/ticket/{0}/'.format(self.id)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM