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

Now in python shell:

from datetime import date

r = Reporter(first_name='John', last_name='Smith', email='john@example.com'
r.save()

new_article = r.article_set.create(headline="John's second story",
pub_date=date(2005, 7, 29))

Above code is referenced from Django docs. If there is any misunderstanding please go to this link.

cezar
  • 11,616
  • 6
  • 48
  • 84
Mohd. Shoaib
  • 113
  • 1
  • 6

1 Answers1

1

article_set is a backward relation to the articles from your reporter object. Django creates this "hidden" fields because of the ForeignKey reporter in your Article model.

See this part of the doc.

If a model has a ForeignKey, instances of the foreign-key model will have access to a Manager that returns all instances of the first model. By default, this Manager is named FOO_set, where FOO is the source model name, lowercased. This Manager returns QuerySets, which can be filtered and manipulated as described in the “Retrieving objects” section above.

You can access the reporter from an article instance like this:

article_instance.reporter

And you can access the articles from a reporter like this:

reporter_instance.article_set.all()
Cyrlop
  • 1,894
  • 1
  • 17
  • 31