Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a child attributes in parent object

Tags:

python

django

I'm fairly new to Django and it seems like there might be an easy and obvious way to do this, but if so I haven't been able to find it.

(Slightly simplified code)

I have a primary class

class Article(models.Model):
    ...

and a secondary class

class Headline(models.Model):
    article = models.ForeignKey(Article)
    headline = models.CharField(max_length=200)

Is there a simple way to get the headline attributes of an Article object (or rather, to get the headline attributes of all the Headline objects associated with the Article object)? I know it would be possible to filter the Headline objects by article attribute, but I suspect that there is a faster and simpler way. Is it possible to add a method to the class Article, for instance, that would return all the associated Headline objects?

like image 835
stillLearning Avatar asked Jan 20 '23 02:01

stillLearning


1 Answers

If you have a single instance of Article, then you can get all of the headline objects with

article.headline_set.all()

This returns a QuerySet that you can use just like any other.

Edit: If you want to get the actual headline value, then just like for any other query set you will need to get a single instance of Headline. For example,

headline = article.headline_set.all()[0].headline

Edit2: As Thibault J points out in the comments, you can get all of the headlines with

headlines = [headline.headline for headline in article.headlines.all()]
like image 162
murgatroid99 Avatar answered Jan 24 '23 11:01

murgatroid99