Search code examples
djangofor-loopforeign-keys

django ForeignKey in for loop


i will like to show data in table from two models with ForeignKey: i will use this models as example:

class Reporter(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    email = models.EmailField()

    def __str__(self):
        return "%s %s" % (self.first_name, self.last_name)

class Article(models.Model):
    headline = models.CharField(max_length=100)
    pub_date = models.DateField()
    reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE)

    def __str__(self):
        return self.headline

    class Meta:
        ordering = ['headline']

and now i will like to have dataTable showing all Reporters last_name , and latest Article headline related to each Reporter

this is my views.py

def reporters(request):
    reporters = Reporter.objects.all()
    total_reporters = Reporter.objects.count()
    context = dict(reporters=reporters, total_reporters=total_reporters)
    return render(request, 'reporters/reporters.html', context)

but this is only giving reporters name

{% for reporter in reporters %}

{{ reporter.last_name }}

{% endfor %}

Solution

  • In your Reporter model write a method to get the latest Article:

    class Reporter(models.Model):
        first_name = models.CharField(max_length=30)
        last_name = models.CharField(max_length=30)
        email = models.EmailField()
    
        def __str__(self):
            return "%s %s" % (self.first_name, self.last_name)
        
        def get_latest_article(self):
            return self.article_set.latest('pub_date')
    

    Now in your template you can write:

    {% with latest_article=reporter.get_latest_article %}
        {{ latest_article.headline }}
        {{ latest_article.pub_date }}
    {% endwith %}
    

    Note: latest may raise a DoesNotExist exception if the reporter has no articles, you may need to use a try-except block to prevent any errors (return None in except block) and check in template if the value is not None.