user2387035
user2387035

Reputation: 79

Django, filter records from model method?

I'm trying to filter records using a model method but am unsure how to implement it in the view.

Should it be done in this way, or completely in the view in some other manor?

Here's my model below:

class Message(models.Model):
    msg_id = models.IntegerField(unique=True)
    user = models.ForeignKey(User)
    message = models.CharField(max_length=300)
    added = models.DateTimeField('added')

    def about_cats(self):
        matches = ['cat', 'kitty', 'meow']
        return any(s in self.message for s in matches)

    def __unicode__(self):
        return self.message

Upvotes: 3

Views: 1019

Answers (2)

karthikr
karthikr

Reputation: 99660

Since you need to filter the queryset object, you can do something like this in your view:

from django.db.models import Q
matches = ['cat', 'kitty', 'meow']
messages = Message.objects.filter(reduce(operator.or_, (Q(message__contains=match) for match in matches)))  #Or use icontains if you want a case insensitive match. 

Upvotes: 2

Emanuele Paolini
Emanuele Paolini

Reputation: 10172

The filter should be a method of a MessageManager. See here: https://docs.djangoproject.com/en/dev/topics/db/managers/

Upvotes: 1

Related Questions