2

UPDATE #2

Status: Still not solved

Updated: Thurs. Dec. 18, 11:30 a.m.

I'm currently using FullArticle.objects.order_by('?').first() to get a random article from my database, but it's not working. There is probably something missing from my models, view or url.py that's missing.

models.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"] 

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

Section in list.html that I want to be random

<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 %} 
4
  • Man, you are very confused...What has order_by to do with randomness? Commented Dec 15, 2014 at 23:30
  • 3
    @MihaiZamfir you are the one who is confused: that is the syntax for asking for items in a random order. Commented Dec 15, 2014 at 23:31
  • You're right. Missjudged in my humble comment. Commented Dec 15, 2014 at 23:41
  • I'm using version 1.7 Commented Dec 16, 2014 at 2:13

3 Answers 3

1

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?

To get specific fields of an object, use values or values_list. The first will return dictionaries, the second tuples:

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

The above would result in something like:

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

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

Not sure what this is about, but try to avoid shadowing built-in libraries, like random.

Sign up to request clarification or add additional context in comments.

Comments

0

1) Actually you almost did it.

try: article = FullArticle.objects.order_by('?')[0] except IndexError: article = None 

2) You could use this in models.py as well as in views.py. IMHO there is no need to extract this string to separate method so I would write this code wherever I need it.

3) Better use ORM don't convert db result to list to choose first item. This is can be really memory and CPU expensive.

2 Comments

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?
Burhan Khalid answered it.
0

Getting a random article would usually be done in a view, or as a modelmanager method, or as a class method. Fullarticle.random should not be a class attribute. That will not work as you expect.

# Used in a view. article = FullArticle.objects.order_by('?').first() # you can also make a random() method in your model manager. def random(self): return self.get_queryset().order_by('?').first() # or as a class method inside FullArticle @classmethod def random(cls): return cls.objects.order_by('?').first() 

I'm not quite sure what exactly you mean by this.

I only want data associated with the specific parts of the article: title, author, heroImage and body. How would I go about doing that?

To access specific attributes you do this:

title = article.title author = article.author 

If you don't need to use article.category, just don't access it.

from django.views.generic import DetailView from books.models import Publisher, Book

To pass data from your (class based) View to the template it has to be added to the context. Here's an example from the official documentation:

class PublisherDetail(DetailView): model = Publisher def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super(PublisherDetail, self).get_context_data(**kwargs) # Add in a QuerySet of all the books context['book_list'] = Book.objects.all() return context 

source: https://docs.djangoproject.com/en/1.7/topics/class-based-views/generic-display/#adding-extra-context

Lots of people find Class Based Views in Django to be a bit confusing. I would recommend that you understand how function based views work before you start doing anything complicated with CBVs.

8 Comments

bad idea to create a method called random as its the name of a standard library.
So is 'email', but that is also an attribute in the django User object. That's why we have name spaces and scopes. It's not really a problem.
random is the name of a method as well.
I'm wondering how to call/ grab this piece of random article now. You guys mentioned that I should be using a tag like this: {{article.title}}, but that doesn't seem to be working. So, I'm assuming my syntax might be off?
What does your view function look like?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.