[Answered ]-Get attribute of a generic foreign key

1πŸ‘

βœ…

It is best to define a method on your targeted models rather than building all the business logic in your NotificationRecipient model.

The logic is that the NotificationRecipient model only needs to know that it requires an email address.

class Client(...):
    def get_email_addr(self):
        return primary_email

class Account(...):
    def get_email_addr(self):
        return email

class NotificationRecipient(models.Model):
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

    def get_email_addr(self):

        try:
            email = self.content_object.get_email_addr()

        # if you want to enforce the attribute
        except AttributeError:
            raise ImproperlyConfigured('Model requires an email address')

        # if you need a default
        if not email:
            return 'default@email.com'

        return email
πŸ‘€Jon Loo

1πŸ‘

You can check the content_type field to determine which kind the object is.

But rather than checking the type, you might consider defining an attribute on all the target models which returns the relevant attribute.

Leave a comment