递归遍历模型



我有一个这样的模型:

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实例,并使用namePython和参考编程parent创建另一个Folder实例,则应该使用"编程"填充编程的path字段,并使用"编程/Python"填充Python。不幸的是,它不起作用

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

我该怎么做。

问题是没有定义get_path,一揽子尝试/除了正在吃掉你的错误。您的方法应该是:

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

这里有一个轻微的优化。如果首先生成父级的路径,则不必反转文件夹名称列表,然后只需在末尾加入即可。

def get_path(self):
yield from self.parent.get_path()
yield self.name
def complete_get_path(self):
return "/".join(self.get_path())

相关内容

  • 没有找到相关文章

最新更新