0

好的,所以我正在使用博客 (zinnia),模型是 Entries。我想制作一个执行以下操作的特殊查询:

  1. 每天最多选择一个条目。
  2. 如果条目标记为“精选”,请选择该条目。
  3. 否则选择最新的

精简型号:

class EntryAbstractClass(models.Model):
    """Base Model design for publishing entries"""
    creation_date = models.DateTimeField(_('creation date'),
                                         default=timezone.now)
    start_publication = models.DateTimeField(_('start publication'),
                                             blank=True, null=True,
                                             help_text=_('date start publish'))
    end_publication = models.DateTimeField(_('end publication'),
                                           blank=True, null=True,
                                           help_text=_('date end publish'))
    featured = models.BooleanField(_('featured'), default=False)

更复杂的是,用于“最新”的输入日期是:

if start_publication != None:
    latest_date = start_publication
else:
    latest_date = creation_date

我不确定如何在 SQL 中执行此操作,更不用说 django 过滤器了。有任何想法吗?

4

1 回答 1

2

嗯,也许使用 Q 对象?我不确定我是否 100% 理解,请查看: https ://docs.djangoproject.com/en/dev/topics/db/queries/

像这样的东西怎么样(完全未经测试):

from datetime import datetime
from django.db.models import Q

filters = Q()

# If an item is featured
filters |= Q(featured=True)

# or if it was "published" today
filters |= Q(start_publication__day=datetime.today())

# or if it was "created" today
filters |= Q(creation_date__day=datetime.today())

# grab just one
entry_of_the_day_yall = Entries.objects.filter(filters)[:1]
于 2013-03-27T02:08:38.717 回答