开发者

Django: generating a queryset of objects from a model, based on objects in another model

开发者 https://www.devze.com 2023-02-12 06:37 出处:网络
I have a model with one field, which references another model - as shown below: from random import randint

I have a model with one field, which references another model - as shown below:

from random import randint
from django.db import models
from django.db.models import Count


class UsersManager(models.Manager):
    def random(self):
        count = self.aggregate(count=Count('id'))['count']
        random_index = randint(0, count - 1)
        return self.all()[random_index]


class Game(models.Model):
    web_name = models.SlugField(max_length=40, unique=True)
    name = models.CharField(max_length=40)
    description = models.TextField()
    category = models.CharField(max_length=2)
    multiplayer = models.BooleanField()
    objects = UsersManager()
    def __unicode__(self):
        return self.name


class Featured(models.Model):
    featured_game = models.ForeignKey(Game, unique=True)
    objects = UsersManager()
    def __unicode__(self):
        return self.featured_game.name

In one of my views I generate querysets to use in my template page, such as

game_list = Game.objects.filter(multiplayer=True)

or

game_list = Game.objects.all()

or

game_list = Featured.objects.all()

Using the last queryset I was under the impression that I would be able to access the Game attributes, and make a for loop within a template, as I did with first 2. However it comes back with a TemplateSyntaxError.

The main reason I've made a new model just for Featured, rather than including it in the main model as a Boolean (like 'multiplayer') is that I need to randomly choose games from both the main list and from the featured list - using the user manager shown above.

Clearly I'm doing something fundamentally wrong, so what is the best way of generating a queryset of Game objects that are in the Featured model?

EDIT:

I am also using paginations, which is perhaps what is causing the issue, here is the code from the end of my view:

paginator = Paginator(game_list, 20) # Show 20 games per page
# Make sure page request is an int.开发者_Python百科 If not, deliver first page.

try:
    page = int(request.GET.get('page', '1'))
except ValueError:
    page = 1

# If page request (9999) is out of range, deliver last page of results.
try:
    games = paginator.page(page)
except (EmptyPage, InvalidPage):
    games = paginator.page(paginator.num_pages)

c = { 
    'games': games,
}
return render_to_response('category.html', c)

Here is the code from the template (note that views is an attribute of Game in my real code):

{% for game in games.object_list %}
<h2>{{ game.name }}</h2>

<h2>{{ game.description }}</h2>

<h2>{{ game.views }}</h2>

{% endfor %}

And here is the specific error message:

Template error

In template /home/jon/templates/category.html, error at line 5
Caught FieldError while rendering: Cannot resolve keyword 'views' into field. Choices are: featured_game, id
1   Game category here
2   
3   <h1>{{ category }}</h1>
4   
5   {% for game in games.object_list %}
6   <h2>{{ game.name }}</h2>
7   
8   <h2>{{ game.description }}</h2>
9   
10  <h2>{{ game.views }}</h2>
11  
12  {% endfor %}


By the way, what syntax error are you talking about?

It's useful to post code.

Yes, all featured games would be available through Featured.objects.all()

{% for featured in featured_games %}
   {{ featured.featured_game }}
{% endfor %}

Note: I would recommend using select_related() to ensure you're only doing a single query. http://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.QuerySet.select_related

To answer your question at the end though, you could do: Game.objects.filter(featured__isnull=False), but I think fixing your template syntax error would be a better solution and using Featured.objects.select_related()

0

精彩评论

暂无评论...
验证码 换一张
取 消