我有两个相互关联的模型。我需要创建一个子文件夹,以通过qa id保留附件。 但我正在努力获取相关对象ID的ID。有人可以帮忙吗?
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')
答案 0 :(得分:1)
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)
使用自定义函数获取qa_id
,然后保存