I have an intermediate model which is as follows -
class Link_Book_Course(models.Model):
book = models.ForeignKey(Book)
course = models.ForeignKey(Course)
image = models.CharField(max_length = 200, null=True)
rating = models.CharField(max_length = 200,null=True)
def __unicode__(self):
return self.title
def save(self):
self.date_created = datetime.now()
super(Link_Book_Course,self).save()
I've created a new Book and a new Link_Book_Course, and am trying to add that book to the Link_Book_Course
call the Link_Book_Course newCourseLink
and call the Book newBook
.
I thought that this call would work -
newCourseLink.book_set.add(newBook)
but Django throws an error saying that newCourseLink has no attribute book_set- does anyone know why?
Furthermore, how can I 开发者_Python百科add the Book to newCourseLink
?
Thanks
The way you have the relationships set up, each Link_Book_Course
(horrible name, BTW) can only have one book. You can't add books, you can only refer to that one book via newCourseLink.book
.
If you wanted each LBC to have multiple books, the FK should go from Book to LBC.
Edit after comment The very point of an intermediate model is that there's one instance of it for every combination of its two FKs. If you want to add new books, you'll need new instances of LBC to go with them. You can change the book the current LBC refers to with just newCourseLink.book = my_new_book
, but as I say you can't add one.
精彩评论