【问题标题】:Django, filter records from model method?Django,从模型方法中过滤记录?
【发布时间】:2013-06-22 11:03:13
【问题描述】:

我正在尝试使用模型方法过滤记录,但不确定如何在视图中实现它。

应该这样做,还是完全在其他庄园的视野中?

下面是我的模型:

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

【问题讨论】:

  • 除了视图之外的任何地方都需要/有用吗?
  • 另外,return any(...).
  • @ignacio 就在 view.py 中。添加了回报。
  • 这里的tweet_content 是什么?
  • @karthikr 应该是“消息”固定

标签: django django-models django-views


【解决方案1】:

由于您需要过滤查询集对象,因此您可以在视图中执行以下操作:

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. 

【讨论】:

  • 你需要导入Q :) from django.db.models import Q
【解决方案2】:

过滤器应该是 MessageManager 的一个方法。见这里:https://docs.djangoproject.com/en/dev/topics/db/managers/

【讨论】:

  • 我之前确实尝试过,将方法放在 MessageManager 类中,然后放在我的模型函数中:objects = MessageManager(),然后在我看来:页面上的 msg_list = Message.objects 结果没有被过滤
猜你喜欢
  • 1970-01-01
  • 2020-02-03
  • 1970-01-01
  • 2011-03-03
  • 2014-09-02
  • 2016-03-10
  • 2011-01-17
  • 1970-01-01
  • 2016-02-28
相关资源
最近更新 更多