1.) 我有以下 models.py 定义:
from django.db import models
from datetime import date
class Author(models.Model):
author = models.CharField(max_length=20)
def __unicode__(self):
return '%s' % (self.author)
class SystemA(models.Model):
author = models.ForeignKey(Author)
date = models.DateField()
system = models.CharField(max_length=20, blank=False, default="System A")
description = models.CharField(max_length=300)
status = models.CharField(max_length=6)
def __unicode__(self):
return '%s, %s, %s, %s, %s' % (self.date, self.author, self.system, self.description, self.status)
class SystemB(models.Model):
author = models.ForeignKey(Author)
date = models.DateField()
system = models.CharField(max_length=20, blank=False, default="System B")
description = models.CharField(max_length=300)
status = models.CharField(max_length=6)
def __unicode__(self):
return '%s, %s, %s, %s, %s' % (self.date, self.author, self.system, self.description, self.status)
2.) 这个 admin.py 定义:
from acc.models import SystemA, SystemB, Author
from django.contrib import admin
admin.site.register(SystemA)
admin.site.register(SystemB)
3.)这是我的views.py定义:
from django.http import HttpResponse
from acc.models import SystemA, SystemB
from django.template import Context, loader
from itertools import chain
from operator import attrgetter
def index(request):
a_list = SystemA.objects.all().order_by('-date')
b_list = SystemB.objects.all().order_by('-date')
result_list = sorted(
chain(a_list, b_list),
key=attrgetter('date'))
t = loader.get_template('index.html')
#c = Context({'result_list': result_list,})
c = Context({'a_list': a_list,'b_list': b_list,})
return HttpResponse(t.render(c))
4.) 最后,呈现静态 HTML 页面 (index.html) 的模板定义为:
{% if a_list %}
<ul>
{% for a in a_list %}
<li>{{a.date}} | {{a.author}} | {{a.system}} | {{a.description}} | {{a.status}}</li>
{% endfor %}
</ul>
{% endif %}
{% if b_list %}
<ul>
{% for b in b_list %}
<li>{{b.date}} | {{b.author}} | {{b.system}} | {{b.description}} | {{b.status}}</li>
{% endfor %}
</ul>
{% endif %}
代码正在运行,我已经从管理界面输入了一些数据。结果:
April 18, 2013 | owta | System A | All jobs went bananas! | FAILED
April 17, 2013 | rash | System A | All Well | OK
April 18, 2013 | owta | System B | All jobs went bananas! | FAILED
April 17, 2013 | rash | System B | All well | OK
我的目标是获得按日期排序的结果,独立于模型(SystemA/SystemB),按以下排序顺序:
April 17, 2013 | rash | System A | All Well | OK
April 17, 2013 | rash | System B | All well | OK
April 18, 2013 | owta | System A | All jobs went bananas! | FAILED
April 18, 2013 | owta | System B | All jobs went bananas! | FAILED
我花了半周的时间试图解决这个问题,但没有成功,而且我是 Django 的菜鸟。一些帮助将不胜感激!谢谢。