递归地遍历模型

Recursively going through a model

我有这样一个模型:

class CustomUser(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    slug = models.SlugField(blank=True)

    def lastfolder(self):
        try:
            return self.folder_set.all().order_by('-created_at')[0]
        except IndexError:
            return None

    def lastdrive(self):
        try:
            return self.drive_set.all().order_by('-created_at')[0]
        except IndexError:
            return None

    def lastfile(self):
        try:
            return self.drive_set.all().order_by('-created_at')[0]
        except IndexError:
            return None

    def save(self, *args, **kwargs):
        self.slug = slugify(self.user.username)
        return super().save(*args, **kwargs)

    def get_absolute_url(self):
        kwargs = {'slug' : self.slug}
        return reverse('', kwargs=kwargs)

    def __str__(self):
        return self.user.username

class Drive(models.Model):
    owner = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
    name = models.CharField(max_length=64)
    cover_picture = models.ImageField(upload_to=f'media/{user_path}', default="media/drive.png")
    created_at = models.DateTimeField()
    slug = models.SlugField(blank=True)

    def get_absolute_url(self):
        kwargs = {'slug' : self.slug}
        return reverse('', kwargs=kwargs)

    def __str__(self):
        return self.name

    def save(self, *args, **kwargs):
        self.slug = slugify(self.name)
        return super().save(*args, **kwargs)

    class Meta:
        unique_together = [['owner', 'name']]
        ordering = ('name',)

class Folder(models.Model):
    owner = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
    drive = models.ForeignKey('Drive', on_delete=models.CASCADE)
    name = models.CharField(max_length=64)
    parent = models.ForeignKey('self', on_delete=models.CASCADE, blank=True, null=True)
    cover_picture = models.ImageField(upload_to=f'media/{user_path}', default="media/folder-white.png")
    created_at = models.DateTimeField()
    path = models.CharField(max_length=2048, blank=True)
    slug = models.SlugField(blank=True)

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        kwargs = {'slug' : self.slug}
        return reverse('', kwargs=kwargs)

    def get_path(self):
        yield self.name
        try:
            yield from get_path(self.parent)
        except:
            pass

    def complete_get_path(self):
        text = []
        for i in self.get_path():
            text.append(i)
        text.reverse()
        return "/".join(text)

    def save(self, *args, **kwargs):
        self.slug = slugify(self.name)
        self.path = self.complete_get_path()
        return super().save(*args, **kwargs)


    class Meta:
        unique_together = [['parent', 'name']]
        ordering = ('name',)

如果我使用 name 编程创建一个 Folder 实例,并使用 name Python 和 parent 创建另一个 Folder 实例参考编程,应该用 "Programming" 填充编程的 path 字段,用 "Programming/Python" 填充 Python 字段。不幸的是,它不起作用

我的重点是 Folder 模型和方法:get_pathcomplete_get_pathsave。 保存模型后,检查管理中的 path 字段,它只显示 name 属性而不是 return 文件夹的实际生成路径。

我该怎么做。

问题是 get_path 未定义,毯子 try/except 正在吞噬你的错误。你的方法应该是:

def get_path(self):
    yield self.name
    yield from self.parent.get_path()

此处稍作优化。如果您先 yield 父路径,则不必反转文件夹名称列表,然后只需在末尾加入即可。

def get_path(self):
    yield from self.parent.get_path()
    yield self.name

def complete_get_path(self):
    return "/".join(self.get_path())