vlad
vlad

Reputation: 855

How merge two queries from unrelated models

I have two unbound models:

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

I know it's dirty code, and I should use ForeignKey but unfortunately, I have no right to touch the models.py file.

How can I combine it into a list?

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

And show it in template:

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

And get something like: <h2>Beer Festival - Germany</h2>?

Upvotes: 2

Views: 912

Answers (1)

jammon
jammon

Reputation: 3464

I understand that News.country refers to Country.id. So you could do something like that:

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

and

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

Doing it in the database would be faster, but this is an easy way and premature optimization ...

Upvotes: 3

Related Questions