Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Instance belonging in Django Model Inheritance

What is the simpliest way to figure out does notification belong to BaseNotification or to ExtendedNotification?

class User(models.Model):
    pass

class BaseNotification(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='notifications')

class ExtendedNotification(BaseNotification):
    pass

# usage
for notification in user.notifications.all():
    # --> here <--

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can distinguish the two by using hasattr(notification, 'extendednotification'). Here’s an example of how to use it with a loop:

for notification in user.notifications.all():
    if hasattr(notification, 'extendednotification'):
        extended_notification = notification.extendednotification
        # do stuff with the extended notification
    else:
        # do stuff with the base notification
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading