'how to access django related field from model methods?
is it possible to access django related field from model methods?
for example, i have an Author with many Books is it possible to access the list of books from a Model Method in Book model.
class Author(models.Model)
name=charfield
def mymodelmethod(self)::
self.book_set????;
class Book:
author = foreignkey(Author)
title = charfield
Solution 1:[1]
Yes, you can do:
def mymodelmethod(self):
self.book_set.all()
Solution 2:[2]
In Python, explicit return
should be used:
class Author(models.Model):
# ...
def mymodelmethod(self):
return self.book_set
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | klautern |
Solution 2 |