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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…