Django视图按日期开始过滤

时间:2016-01-22 17:11:52

标签: python django

我有一个这样的模型标签:

date_realization = models.DateField(_('Realised in'),
                                     default=timezone.now)

然后是这样的网址:

    url(r'^date/(?P<daterealization>[\w\.@+-]+)/$', DateEntriesView.as_view(), name='articles-date'),

当我发送网址时,就像这样:

  

www.mondomaine.com/articles/date/2016-01

我的date_realization字段是这样的:

  

2016年1月13日

我想要做的就是返回所有有此日期的文章。

所以我尝试了我为类别所做的事情,但这里的行为有点不同。 这就是我试图做的事情:

class DateEntriesView(ContextSourcesMixin, BaseArticleView, BaseArticleListView):
model = Article
context_object_name = 'article_list'
template_name = 'base_templates/template_press.html'
_date_realization = None
paginate_by = None
view_url_name = 'djangocms_press:articles-date'

def get(self, *args, **kwargs):
    # submit object to cms toolbar to get correct language switcher behavior
    if hasattr(self.request, 'toolbar'):
        self.request.toolbar.set_object(self.date_realization)
    return super(DateEntriesView, self).get(*args, **kwargs)

@property
def date_realization(self):
    if not self._date_realization:
        try:
            date_realization_qs = Article.objects.active_translations(
                get_language(),
                date_realization__startswith=self.kwargs['daterealization']
            )

            self._date_realization = date_realization_qs.latest('pk')
        except Article.DoesNotExist:
            raise Http404("Article does not exist for this site")
    return self._date_realization

def get_queryset(self):
    qs = super(DateEntriesView, self).get_queryset()
    if 'date_realization' in self.kwargs:
        qs = qs.filter(date_realization__pk=self.date_realization.pk)
    return qs

def get_context_data(self, **kwargs):
    kwargs['date_realization'] = self.date_realization
    return super(DateEntriesView, self).get_context_data(**kwargs)

但我得到了这条例外消息:

  

异常类型:/ en / press / date / 2016-01 /

中的FieldError      

异常值:关系字段不支持嵌套查找

因此,我感到困惑。

编辑:

嗯,模型文章很长,

@version_controlled_content
@python_2_unicode_compatible
class Article(ModelMeta, TranslatableModel):
taints_cache = True

"""
Press article element,
"""
date_created = models.DateTimeField(auto_now_add=True)
date_modified = models.DateTimeField(auto_now=True)
date_realization = models.DateField(_('Realised in'),
                                     default=timezone.now)
image = FilerImageField(verbose_name=_('Featured image'), blank=True,
                             null=True,
                             on_delete=models.SET_NULL,
                             related_name='image_press_article',
                             help_text=_('Set if the article will be featured'))

sources = models.ManyToManyField(ArticleSource, verbose_name=_('Source'),
                                    blank=False, null=True, related_name='sources_press_article')

regions = models.ManyToManyField(Country, verbose_name=_('Country of the article'),
                                 blank=True, null=True,
                                 related_name='regions_press_article')

global_regions = models.BooleanField('Global', default=False)

featureArticle = models.BooleanField(_('Feature'), help_text=_('Feature this article'), default=False)

sites = models.ManyToManyField(Site, verbose_name=_('Sites'), blank=True,
                                                    null=True,
                                                    help_text=_('Select sites in which show the project.'))

article_url = models.CharField(_('Article Url'), max_length=310, blank=False,
                                   help_text=_('Use to link to the original source'))

countries_displayed_in = models.ManyToManyField(
    Country,
    verbose_name=_('Countries displayed in'),
    blank=True,
    null=True,
    related_name='displayed_in_press_article',
    help_text='Select the countries in which this project will be visible.'
    'If not selected, the project will be visible in all countries otherwise it will be'
    'visible only for users that are located in the countries selected')

translations = TranslatedFields(
    title=models.CharField(_('title'), max_length=510),
    slug=models.SlugField(_('slug'), blank=False, db_index=True, max_length=300),
    description=HTMLField(_('article description if featured'), default='', blank=True,
                          configuration='HTMLFIELD_CKEDITOR_SETTINGS_CONTENT'),

    meta_description=models.TextField(verbose_name=_('article meta description'),
                                      blank=True, default=''),
    meta_keywords=models.TextField(verbose_name=_('article meta keywords'),
                                   blank=True, default=''),
    meta_title=models.CharField(verbose_name=_('article meta title'),
                                help_text=_('used in title tag and social sharing'),
                                max_length=255,
                                blank=True, default=''),
    meta={'unique_together': (('language_code', 'slug'),)}
)

objects = ProjectManager()

_metadata = {
    'title': 'get_title',
    'description': 'get_description',
    'keywords': 'get_keywords',
    'locale': None,
    'image': 'get_image_full_url',
    'published_time': 'date_created ',
    'modified_time': 'date_modified',
    # Handle the get_absolute_url in the view to have access to the request
    # and so, to the current_app namespace instance
    # 'url': 'get_absolute_url',
}

def country(self):
    return "\n".join(([p.name for p in self.regions.all()]))

def source(self):
    return "\n".join([p.name for p in self.sources.all()])

def get_title(self):
    title = self.safe_translation_getter('meta_title', any_language=True)
    if not title:
        title = self.safe_translation_getter('title', any_language=True)
    return title.strip()

def get_keywords(self):
    return self.safe_translation_getter('meta_keywords').strip().split(',')

def get_description(self):
    description = self.safe_translation_getter('meta_description', any_language=True)
    if not description:
        description = self.safe_translation_getter('description', any_language=True)
    return escape(strip_tags(description)).strip()

def get_image_full_url(self):
    if self.image:
        return self.image.url
    return ''

class Meta:
    verbose_name = _('Press article')
    verbose_name_plural = _('Press articles')
    get_latest_by = 'date_realization'

def __str__(self):
    title = self.safe_translation_getter('title', any_language=True)
    return title if title is not None else '(not translated)'

def save(self, *args, **kwargs):
    super(Article, self).save(*args, **kwargs)
    main_lang = self.get_current_language()
    for lang in self.get_available_languages():
        self.set_current_language(lang)
        if not self.slug and self.title:
            self.slug = slugify(self.title)
    self.set_current_language(main_lang)
    self.save_translations()

def get_slug(self):
    return self.safe_translation_getter(
        'slug',
        language_code=get_language(),
        any_language=False)

1 个答案:

答案 0 :(得分:0)

我会通过urlconf解析日期的月份/年份。

 url(r'^date/(?P<date_year>[0-9]+)-(?P<date_month>[0-9]+)/$', 
                     DateEntriesView.as_view(), name='articles-date'),

然后在你看来:

date_realization_qs = Article.objects.active_translations(
                get_language(),
                date_realization__month=self.kwargs['date_month'],
                date_realization__year=self.kwargs['date_year']
            )

请注意,如果您尝试拨打不存在self.kwargs的密钥,则会收到错误消息。如果没有提供默认的当前月份(以及每年调用相同的月份),或许最好将self.kwargs.get('date_month',datetime.date().month)调用为当月。