Reputation: 384
I have these two models related to each other. I need to create a sub folder to keep my attachment by qa id. but I'm struggling with getting id of the related objects id. Can someone please help?
class Qa(models.Model):
question_text = models.CharField(max_length=1000, verbose_name='Q')
answer_text = models.TextField(blank=True, verbose_name='A')
class Attachment(models.Model):
qa = models.ForeignKey('Qa', blank=True, null=True, on_delete=models.CASCADE, related_name='files' )
attach_file = models.FileField(upload_to=f'qa_data/{qa_id}/', null=True, verbose_name='Attachment')
Upvotes: 1
Views: 42
Reputation: 27513
def directory_path(instance, filename):
return 'qa_data_{0}/{1}'.format(instance.qa.id, filename)
class Attachment(models.Model):
attach_file = models.FileField(upload_to=directory_path)
use a custom function to get the qa_id
and then save it
Upvotes: 1