How to access the field of a model which sits in 2 ForeignKey connections to the model, from where it being accessed?
Question might sound confusing but here is what I want to do. So, I somehow want to access the name of the course from the lesson model to create a file path to save videos
class Course(models.Model):
name = models.CharField(max_length=80)
...
class Section(models.Model):
name = models.CharField(max_length=80)
course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name='sections')
...
class Lesson(models.Model):
name = models.CharField(max_length=80)
section = models.ForeignKey(Section, on_delete=models.CASCADE)
video = models.FileField(upload_to=f'courses/{section.course.name}/{section.name}/')
Interpreter does not complain when I want to access the name of a section through this: section.name
. But when I try the same approach and try to access the course name
section.course.name
I get this error:
video = models.FileField(upload_to=f'courses/{section.course.name}/{section.name}/')
AttributeError: 'ForeignKey' object has no attribute 'course'
So what would be the best approach to access the name field of a course model? Thanks in advance!!!
Try doing this:
x = Lesson.objects.get(pk=1)
print('SECTION_NAME', x.section)
print('COURSE_NAME', x.section.course)