【问题标题】:How merge two queries from unrelated models如何合并来自不相关模型的两个查询
【发布时间】:2011-06-05 12:41:32
【问题描述】:

我有两个未绑定的模型:

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 %}

然后得到类似:&lt;h2&gt;Beer Festival - Germany&lt;/h2&gt;?

【问题讨论】:

    标签: django django-views


    【解决方案1】:

    我了解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 %}
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-30
      • 2010-09-23
      • 2020-01-11
      • 2018-06-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多