我有一个称为“游戏”的模型,其中有许多由模型帖子连接的帖子。当我按发布的日期对游戏进行排序时,它会返回来自模型游戏的重复项。我想知道如何在最新发布日期之前显示游戏,而不会返回重复项。
Views.py
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#">Just a pound (should not log anything to the console)</a><br>
<a href="#more">More than a pound (should log "heavy" to the console, and take you to Heavy)</a><br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<p id="more">Heavy</p>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
Models.py
from django.shortcuts import render, get_object_or_404
from library.models import Game
from .models import Post
from django.views.generic import (
ListView,
DetailView
)
# Create your views here.
def home(request):
context = {
'recent': Game.objects.all().order_by('-post__date_published')[:5],
'posts': Post.objects.all(),
}
return render(request, 'main/home.html', context)
class TitlePostListView(ListView):
model = Post
template_name = 'main/title_posts.html'
context_object_name = 'posts'
paginate_by = 5
def get_queryset(self):
title = get_object_or_404(Game, title=self.kwargs.get('title'))
return Post.objects.filter(game=title).order_by('-date_published')
def get_context_data(self, **kwargs):
context = super(TitlePostListView, self).get_context_data(**kwargs)
context['game'] = get_object_or_404(Game, title=self.kwargs.get('title'))
return context
class PostDetailView(DetailView):
model = Post
答案 0 :(得分:0)
您在这里寻找的是distinct()
。
Game.objects.all().order_by('-post_set__date_published').distinct()[:5]
我也看不到您将Post
和Game
连接的位置,因此我假设您正在使用尚未发布的其他代码进行操作,并且当前使用的{{ 1}}在工作。