Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
341 views
in Technique[技术] by (71.8m points)

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 %}
question from:https://stackoverflow.com/questions/66066997/django-foreignkey-in-for-loop

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...