Padoga
Padoga

Reputation: 535

How to filter a Django model based on requirement from another model?

I'd like to retrieve all my contacts from my Contact model excluding those listed on my DoNotContact model. Is the following the most efficient way to do that: contacts = Contact.objects.filter(dont_contact=False) Wondering if this is going to take long to process, is there a more efficient way?

class Contact(models.Model):
    email = models.CharField(max_length=12)
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    audience = models.ForeignKey(Audience, on_delete=models.CASCADE)

    def dont_contact(self):
        try:
            get_object_or_404(DoNotContact, email=self.email)
            return True
        except:
            return False


    def __str__(self):
        return self.email

class DoNotContact(models.Model):
    email = models.CharField(max_length=12)


#views.py
def send_email(request):
    if request.method == "POST":
        contacts = Contact.objects.filter(dont_contact=False)

Upvotes: 0

Views: 35

Answers (1)

partizaans
partizaans

Reputation: 305

Kwargs used model queryset filter methods are resolved into database columns. dont_contact here is a method and doesn't exist as a column in Contact model so calling Contact.objects.filter(dont_contact=False) will raise a FieldError.

For current implementation of your models you can do following

dont_contacts = DoNotContact.objects.values('email')
contacts = Contact.objects.exclude(email__in=dont_contacts)

A better solution with higher performance is to remove DoNotContact and add a BooleanField to Contact which handles your requirement.

Upvotes: 1

Related Questions