Padoga
Padoga

Reputation: 535

How to get my Django template to recognize a model method?

In my django template <p>This user is unsubscribed {{sub.is_unsubscribed}}</p> always displays "This user is unsubcribed False" even when it should show True based on the following models.py

from django.shortcuts import get_object_or_404

class Subscriber(models.Model):
    email = models.CharField(max_length=12)
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    create_date = models.DateTimeField(auto_now_add=True)

    def is_unsubscribed(self):
        try:
            get_object_or_404(MasterUnsubscriber, unsubcriber_email=self.email)
            return True
        except:
            return False


    def __str__(self):
        return self.email

class MasterUnsubscriber(models.Model):
    unsubscriber_email= models.CharField(max_length=12)

And for structural reasons of my app, I do not want to move the unsubscribe to the Subscriber model as a boolean. How can this be resolved while keeping same model formats.

Upvotes: 1

Views: 38

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476614

get_object_or_404 will raise an error if there is no element at all, or when there are multiple such elements, since the underlying implementation is to use .get(..). You can make use of .exists() instead:

class Subscriber(models.Model):
    # …

    def is_unsubscribed(self):
        return MasterUnsubscriber.objects.filter(unsubscriber_email=self.mail).exists()

That being said, I would advice to make use a ForeignKey [Django-doc] to the subscriber, not by matching the email address. This will be inefficient, since search on a non-indexed column is slow, and furthermore if the user later changes their email, then the all of a sudden, these can be subscribed again. Django also has convenient ways to filter or make aggregates on related objects, so you get more out of the Django ORM.

Upvotes: 1

Related Questions