-1

I am trying to add OneToMany field in django rest models. But Django is not giving an options for it. Can anyone suggest something similar to java @OneToMany in Django framework

bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118
Suthanth DK
  • 127
  • 2
  • 8
  • Possible duplicate of [How to express a One-To-Many relationship in Django](https://stackoverflow.com/questions/6928692/how-to-express-a-one-to-many-relationship-in-django) – PyPingu Jun 24 '19 at 14:17
  • 3
    " But Django is not giving an options for it. " => of course it is - how could an ORM skip something so obviously important ? It's spelled "ForeignKey". – bruno desthuilliers Jun 24 '19 at 14:34

1 Answers1

0

You can use related_name in ForeignKey field to achieve this. For example, you have the following models:

class Author(models.Model):
    name = models.CharField(max_length=128)


class Book(models.Model):
    name = models.CharField(max_length=128)
    author = models.ForeignKey(Author, related_name='books', on_delete=models.CASCADE)

Now, to access all books of an author the query will be Author.books.all(). Here, notice that Author model don't have books attribute. But in author ForeignKey field (which refers the Author model) of Book model has the related_name argument and its value is books. It means that books of an auhtor can be accessed from Author model. Django handles it nicely.

Also, you can use select_related for optimization (in this case you don't need to use related_name argument): Book.objects.all().select_related('author')

  • Thanks for the answer. This is working. I also found one more solution for this. We can use _set method for the same. In the above example to access all the books from an author we can do something like, author.book_set.all(). This will fetch all the books of a particular author. – Suthanth DK Jun 26 '19 at 07:47