使用Django 1.6,我有一个基于类的视图来查看日志。有了它,我有2个不同的query_sets ...用于排序最早的日期和最近的日期。我稍后会添加几个查询集。
我如何在网址中放置一个slug并让基于类的视图ViewLog()获取该slug并根据它使用相应的query_set?
此外,基于slug的if-then语句似乎很麻烦,但唯一的另一种选择是让不同的url为特定的query_set调用单独的类......这看起来更麻烦。
url(r'^log_view/(w+)$', ViewLog.as_view(),
name = "log_view"),
models.py:
class LogMostRecent(models.Manager):
def get_queryset(self):
return super(Log, self).get_queryset().order_by("date_stamp")
class LogLeastRecent(models.Manager):
def get_queryset(self):
return super(Log, self).get_queryset().order_by("-date_stamp")
class Log(models.Model):
IRC_MESSAGE_LENGTH = 512
date_stamp = models.DateTimeField()
irc_name = models.ForeignKey(Employee,
related_name='irc_name_log')
message = models.CharField(max_length=IRC_MESSAGE_LENGTH)
objects = AddLogEntry()
most_recent = LogMostRecent()
least_recent = LogLeastRecent()
views.py:
class ViewLog(LoginRequiredMixin, ListView):
template_name = "bot_data/log_view.html"
model = Log
答案 0 :(得分:1)
最好的方法是从你正在使用的slug中选择ListView' get_queryset中的查询集,这样你就不会创建一大堆类似的视图,为每个视图指定一个查询集
答案 1 :(得分:1)
urls.py
url(r'^log/(?P<slug>[-_\w]+)/$', ViewLog.as_view(), name="log_name"),
views.py
class ViewLog(LoginRequiredMixin, ListView):
template_name = "bot_data/log_view.html"
#model = Log
#context_object_name = 'log_index'
def get_queryset(self):
self.log = get_object_or_404(Log, slug=self.args[0])
return Log.objects.filter(your_slug_in_model=self.log)
#def get_context_data(self, **kwargs):
...