In the django document https://docs.djangoproject.com/en/3.2/topics/db/examples/many_to_one/, there are two tables, Report and 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)
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']
My question, if you have a list of Reports, how would you get their articles? I've tried
articles = []
for report in reports:
article = Article.objects.filter(report = report)
articles.append(article )
but this does not give me all my data.
class Article(models.Model):
headline = models.CharField(max_length=100)
pub_date = models.DateField()
reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE, related_name="articles")
Then you can just do reporter.articles.all()
Note: if your ForeignKey field doesn't have a related_name attribute, you can get the reverse relatioship by calling <model_name>_set. For example: reporter.article_set.all()