我不知道如何创建查询集,以便为表 字段URLusage
中的每个 URL 拾取最后一个表条目,并将其附加到类似于我对该字段所做的查询结果中。RedirectURL
dateaccessed
num_links
最终结果是我显示了一个 RedirectURL 列表,其中包含表中的使用次数和上次使用日期URLusage
。
谢谢你。
例如。
链接---上次使用---总使用
xxxxx 2020 年 12 月 13 日 22
年年 2020 年 1 月 14 日 2
楷模
class RedirectURL(models.Model):
userid = models.PositiveBigIntegerField(null=True, default=1)
srcurl = models.CharField(max_length=50, null=True, unique=True)
active = models.BooleanField(null=True, default=False)
class URLusage(models.Model):
redirectid = models.ForeignKey(RedirectURL, on_delete=models.CASCADE)
dateaccessed = models.DateTimeField(auto_now_add=True, null=True)
看法
class LinksList(LoginRequiredMixin, ListView):
login_url = "home"
redirect_field_name = None
login_required = True
context_object_name = 'links'
paginate_by = 30
template_name = 'yourlinks.html'
paginate_orphans = 1
def get_queryset(self):
return RedirectURL.objects.filter(userid=self.request.user.id, active=True).annotate(num_links=Count('urlusage')).order_by('-id')
def get_context_data(self,*args, **kwargs):
try:
return super(LinksList,self).get_context_data(*args, **kwargs)
except Http404:
self.kwargs['page'] = 1
return super(LinksList,self).get_context_data(*args, **kwargs)
模板
{% for i in links %}
<div class="row">
<div class="col-sm">
{{ i.srcurl }}
</div>
<div class="col-sm">
{{ i.last_dateaccessed }}
</div>
<div class="col-sm">
{{ i.num_links }}
</div>
</div>
{% endfor %}