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?
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()]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With