0

所以,我有一个模型项目,它有它的所有者(用户)。每个项目都有自己的 FilePathField,这取决于所有者(不同用户的 FilePathField 的“匹配”参数不同)。但这并不是唯一遵循这一原则的模型。

我可以重写构造函数(__ init __函数)并将用户传递到那里。

我也可以创建工厂来创建这些模型。

在这种情况下,严肃的人会做什么?(当他们必须根据用户更改模型的字段属性时)

模型:

class Project(models.Model):
    project_file = models.FilePathField(_("Project file"), match='\.prj$', allow_files=True,
                                        allow_folders=False, recursive=True, path=PROJECTS_ROOT, null=False)
    name = models.CharField(_("Project name"), max_length=80, null=False)
    owner = models.ForeignKey(User, verbose_name=_("Owner"), null=False)

类似工厂功能的东西(只是解决方法):

def getUserProjectForm(data, user=None):
    class ProjectForm(forms.ModelForm):
        def __init__(self, *args, **kwargs):
            forms.ModelForm.__init__(self, *args, **kwargs)
            try:
                user_folder = str(user.id)
                root_path = join(PROJECTS_ROOT, str(user_folder))
            except Exception as e:
                user_folder = None
                root_path = PROJECTS_ROOT
            self.fields['project_file'].path = root_path
            self.filter_paths(user_folder)

        class Meta:
            model = Project
            fields = ['name', 'project_file']

        def filter_paths(self, user_folder=None):
            import re

            if user_folder is not None and str(user_folder) != '':
                directory = join(PROJECTS_ROOT, str(user_folder))
            else:
                directory = PROJECTS_ROOT
            regexp = re.compile('^%s(.+)$' % directory)
            temp_choices = []
            db_choices = Project.objects.values_list('project_file', flat=True)
            for choice in self.fields['project_file'].choices:
                cur_match = regexp.match(choice[0])
                if cur_match:
                    if choice[0] in db_choices:
                        continue
                    cur_choice = cur_match.groups()[0]
                    print "DEBUG"
                    print choice[0], cur_choice, user_folder
                    print "DEBUG"
                    temp_choices.append((choice[0], cur_choice.replace(separator, "", 1)))
            self.fields['project_file'].choices = temp_choices

还。也许有人知道如何排除数据库中已经存在的文件?(最后一个循环)

4

0 回答 0