如何访问信号中的path_after
字段?
模型:
class Store(models.Model):
user = models.ForeignKey(User)
path = models.FileField(upload_to="src")
path_after = models.FileField(upload_to="files",blank=True, null=True)
class Document(models.Model):
rootfile = models.ForeignKey(Store)
content = models.TextField()
信号:
@receiver(post_save, sender=Store)
def my_handler(sender, **kwargs):
if kwargs['created']:
document = Document()
document.rootfile = kwargs['instance']
#how to open file from path_after field?
text_file = open("path_after", "r")
document.content = #should be text from path_after file, this is TextField
document.save()
答案 0 :(得分:2)
您在instance
的对象的信号处理程序中得到Store
并且它具有path_after
字段。您可以直接访问它:
@receiver(post_save, sender=Store)
def my_handler(sender, **kwargs):
if kwargs['created']:
document = Document()
document.rootfile = kwargs['instance']
#how to open file from path_after field?
text_file = open(kwargs['instance'].path_after.path, "r")
...
答案 1 :(得分:1)
@receiver(post_save, sender=Store)
def my_handler(sender, instance, *args, **kwargs):
if kwargs['created']:
document = Document()
document.rootfile = instance
#how to open file from path_after
text_file = open(instance.path_after, "r")
document.content = #should be text from path_after file, this is TextField
document.save()