1

Django ForeignKey need to grouping

from django.db import models

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',)

I want to list of all reporter with their all article showing the below format. How It possible?

-------------------------------
Reporter Name |  Total Article
-------------------------------
Reporter 1    |   3
-------------------------------
Reporter 2    |   4
-------------------------------
Russell
  • 1,624
  • 5
  • 23
  • 43

1 Answers1

1

If you want to list all reporters you can use Reporter.objects.all() it will return you a queryset of all reporters, and for getting Articles of them use reverse relationship i.e - reporter_object.article_set because you didn't define any related name. see this

I can give you an simple example how you can print All reporters with their Articles -

for reporter in Reporter.objects.all():
    print(reporter)
    for article in reporter.article_set.all():
        print(article)

when you defined a ForeignKey relationship, a one to many relationship is created between Reporter and Article, additionally one more attribute is added in Reporter, by default it is the name of your model with the suffix _set i.e article_set but when you specify the related_name then that will be same as your related_name, now you can easily call article by its related name with object of Reporter.

Still have any doubts comment it.

Pankaj Sharma
  • 2,185
  • 2
  • 24
  • 50