如何合并来自不相关模型的两个查询

时间:2011-06-05 12:41:33

标签: django django-views

我有两个未绑定的模型:

class News(models.Model):
    name = models.CharField(max_length=255, blank=True, null=True)
    text = models.TextField(blank=True, null=True)
    country = models.IntegerField(max_length=255, blank=True, null=True) # 1, 2, 3, etc.

class Countries(models.Model):
        name = models.CharField(max_length=255, blank=True, null=True) # USA, Canada

我知道这是脏代码,我应该使用ForeignKey但不幸的是,我无权触摸models.py文件。

如何将其合并到列表中?

def show_news(request):
    news_list = News.objects.all()
    countries_list = Countries.objects.all()
    # like news_list = news_list + countries_list
    return render(request, 'table_adsl.html', {'news_list': news_list})

并在模板中显示:

{% for news in news_list %}
    <h2>{{news.title}} - {{news.country}}</h2>
    ...
{% endfor %}

得到类似的内容:<h2>Beer Festival - Germany</h2>

1 个答案:

答案 0 :(得分:2)

我理解News.country是指Country.id。所以你可以这样做:

def show_news(request):
    news_list = News.objects.all()
    countries_list = Countries.objects.all()
    countries = dict([(c.id, c.name) for c in countries_list])
    for n in news_list:
        n.country_name = countries.get(n.country, '(no country)')
    return render(request, 'table_adsl.html', {'news_list': news_list})

{% for news in news_list %}
    <h2>{{news.title}} - {{news.country_name}}</h2>
    ...
{% endfor %}

在数据库中执行它会更快,但这是一种简单的方法和过早的优化...