gpt4 book ai didi

python - order.by ('?' ) .first() 在 Django 中获取随机内容时出现问题

转载 作者:太空宇宙 更新时间:2023-11-04 08:58:55 26 4
gpt4 key购买 nike

更新#4:

  • slider.html 中的 for 循环当前未在上次更新后提取内容。 Slider.html 是随机的;但是,我得到了四个相同的故事,并且这些 URL 不再转到它们相应的详细 View 页面。
  • List.html 已修复,现在是随机的。

slider.html - 这部分仍然不稳定,(更新 - 下午 4:19)

{% for random_article in random_articles %}
<div class="slider">
<div class="group visible">
<div class="sliderItem">
<a href="{%url "detailed" slug=random_article.slug %}"><img src="{{random_article.relatedImage}}" alt="" class="sliderPicture"></a>
<a href="{%url "detailed" slug=random_article.slug %}"><p class="related">{{random_article.title}}</p></a>
</div><!-- /.sliderItem -->
</div><!-- /.group -->
</div><!-- /.slider -->
{% endfor %}

这是我点击详细 View 时的 URL 错误:

NoReverseMatch at /last-us
Reverse for 'detailed' with arguments '()' and keyword arguments '{u'slug': ''}' not found. 1 pattern(s) tried: ['(?P<slug>\\S+)']

新罪魁祸首(为什么 slider.html 不起作用)

网址.py

from django.conf.urls import patterns, url
from . import views

urlpatterns = patterns(
'',
url(r'^$', views.BlogIndex.as_view(), name="list"),
url(r'^(?P<slug>\S+)', views.BlogDetail.as_view(), name="detailed"),
)

views.py(更新 - 下午 4:19)

添加了 context['random_slider'] = FullArticle.objects.order_by('?')[:4] 但我认为这不是正确的方法。这样我就可以随机获得四篇不同的文章与四篇相同的文章。

from django.views import generic
from . import models
from .models import FullArticle

# Create your views here.
class BlogIndex(generic.ListView):
queryset = models.FullArticle.objects.published()
template_name = "list.html"

def get_context_data(self, **kwargs):
context = super(BlogIndex, self).get_context_data(**kwargs)
context['random_article'] = FullArticle.objects.order_by('?').first()
return context

class BlogDetail(generic.DetailView):
model = models.FullArticle
template_name = "detailed.html"

def get_context_data(self, **kwargs):
context = super(BlogDetail, self).get_context_data(**kwargs)
context['object_list'] = models.FullArticle.objects.published()
return context

def get_context_data(self, **kwargs):
context = super(BlogDetail, self).get_context_data(**kwargs)
context['random_articles'] = FullArticle.objects.exclude(
pk=self.get_object().pk
).order_by('?')[:4]
return context

原始问题

我正在使用 FullArticle.objects.order_by('?').first() 从我的数据库中获取一篇随机文章,但当我刷新页面时它当前给出的是同一篇文章。我的模型、 View 或我在 list.htmlslider.html 中调用它的方式(使用切片)可能缺少某些东西导致了问题。

我希望在页面加载时随机生成的两个部分:

list.html(已更改为 {{random_article.}} )- 这部分问题已修复。

<div class="mainContent clearfix">
<div class="wrapper">
<h1>Top 10 Video Games</h1>
{% for article in object_list|slice:":1" %}
<p class="date">{{article.pubDate|date:"l, F j, Y" }}</p> | <p class="author">{{article.author}}</p>
<a href="{%url "detailed" slug=article.slug %}"><img src="{{article.heroImage}}" alt="" class="mediumImage"></a>
<p class="caption">{{article.body|truncatewords:"80"}}</p>
{% endfor %}

模型.py

from django.db import models
from django.core.urlresolvers import reverse

# Create your models here.
class FullArticleQuerySet(models.QuerySet):
def published(self):
return self.filter(publish=True)

class FullArticle(models.Model):
title = models.CharField(max_length=150)
author = models.CharField(max_length=150)
slug = models.SlugField(max_length=200, unique=True)
pubDate = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
category = models.CharField(max_length=150)
heroImage = models.CharField(max_length=250, blank=True)
relatedImage = models.CharField(max_length=250, blank=True)
body = models.TextField()
publish = models.BooleanField(default=True)
gameRank = models.CharField(max_length=150, blank=True, null=True)

objects = FullArticleQuerySet.as_manager()

def __str__(self):
return self.title

def get_absolute_url(self):
return reverse("FullArticle_detailed", kwargs={"slug": self.slug})

class Meta:
verbose_name = "Blog entry"
verbose_name_plural = "Blog Entries"
ordering = ["-pubDate"]

最佳答案

问题是您是在“编译时”而不是每次调用 View 时设置类属性的值。相反,你可以这样做:

class BlogIndex(generic.ListView):
queryset = models.FullArticle.objects.published()
template_name = "list.html"

def random_article(self):
return = FullArticle.objects.order_by('?').first()

或者:

class BlogIndex(generic.ListView):
queryset = models.FullArticle.objects.published()
template_name = "list.html"

def get_context_data(self, **kwargs):
context = super(BlogIndex, self).get_context_data(**kwargs)
context['random_article'] = FullArticle.objects.order_by('?').first()
return context

[更新]

In list html, I only need one random article. In slider.html, I need four random articles, would I just tack on FullArticle.objects.order_by('?')[:4] somewhere in that def get_context_data snippet?

是的。在 View 中将其设为复数(不要忘记从副列表中排除主要文章):

class BlogDetail(generic.DetailView):
model = models.FullArticle
template_name = "detailed.html"

def get_context_data(self, **kwargs):
context = super(BlogDetail, self).get_context_data(**kwargs)
context['random_articles'] = FullArticle.objects.exclude(
pk=self.get_object().pk
).order_by('?')[:4]
return context

在模板中,执行:

{% for random_article in random_articles %}
<div class="sliderItem">
<a href="{%url "detailed" slug=random_article.slug %}"><img src="{{random_article.relatedImage}}" alt="" class="sliderPicture"></a>
<a href="{%url "detailed" slug=random_article.slug %}"><p class="related">{{random_article.title}}</p></a>
</div><!-- /.sliderItem -->
{% endfor %}

关于python - order.by ('?' ) .first() 在 Django 中获取随机内容时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27553808/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com