Skip to main content
 首页 » 编程设计

python之使用 Django 从 View /对象列表中获取随机项目

2025年05月04日9wuhuacong

更新#2

状态:仍未解决

更新时间:周四。 12 月 18 日上午 11:30

我目前正在使用 FullArticle.objects.order_by('?').first() 从我的数据库中获取随机文章,但它不起作用。我的模型、 View 或 url.py 中可能缺少某些内容。

模型.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 .py
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"  
    randomArticle = FullArticle.objects.order_by('?').first() 
 
class BlogDetail(generic.DetailView): 
    model = models.FullArticle 
    template_name = "detailed.html" 

urls.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"), 
) 

list.html 中我想要随机的部分

<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 %} 

请您参考如下方法:

I assume that FullArticle.objects.order_by('?')[0] will give me a random item from my class of FullArticle. But, let's say that out of my model, I only want data associated with the specific parts of the article: title, author, heroImage and body. How would I go about doing that?

要获取对象的特定字段,请使用 values or values_list .第一个将返回字典,第二个元组:

FullArticle.objects.order_by('?').values('title','author','heroImage','body').first() 

上面的结果会是这样的:

{'title': 'Foo', 'author': 'Foo Author', ... } 

I've also tacked on your suggestion of random = FullArticle.objects.order_by('?')[0] called it "random" instead.

不确定这是什么意思,但尽量避免隐藏内置库,例如 random .