【问题标题】:limit_choices_to within Django modelDjango模型中的limit_choices_to
【发布时间】:2015-11-29 10:52:35
【问题描述】:

我有一个项目模型。该项目包含人员(从事该项目的人员)。我也在尝试为每个项目人员制作一个模型,包括他们对项目的任何注释和项目完成百分比。

我的问题是我想将individual_person_in_project 过滤到仅对应项目中的人员。我正在尝试使用

limit_choices_to = {'person_in_project':User}

我想将我的选择限制在我的Project 模型中的用户。

class Project(models.Model):
    project_name = models.CharField(max_length = 120,null = False,blank = False)
    project_percent_complete = models.IntegerField(blank = True,null = True, default = 0)
    person_in_project = models.ManyToManyField(User,related_name = 'project_person',blank = True)
    project_description = models.CharField(max_length = 300,null = True,blank = True)

class Project_Person(models.Model):
    corresponding_project = models.ForeignKey(Project,related_name = 'corresponding_project_this_user_is_in',null = False)
    individual_person_in_project = models.ForeignKey(User, related_name = 'a_person_within_the_corresponding_project', limit_choices_to = {'person_in_project':User})
    percent_complete = models.IntegerField(default = 0)

【问题讨论】:

  • 你是在用表单创建对象吗?
  • 我没有在表单中做任何事情。
  • 看来你的设计最好去掉Project模型的person_in_project字段,让链接一个人到一个项目的Project_Person对象的存在成为一个记录项目中的人。一方面,您的数据会更加规范化,甚至可能更具吸引力,上述问题就会消失,因为ProjectPerson 不必跟踪person_in_project
  • 另外,顺便说一下,Python 中的类以及 Django 中的模型类的标准约定不是使用下划线,而是使用 CamelCase——所以 Project_Person 将是 ProjectPerson .

标签: django model foreign-keys limit-choices-to


【解决方案1】:

我在上面留下了评论,但我认为这是一个更好的答案,无论如何:

您可以使用the through option 来跟踪关于多多字段的额外信息,这样您就可以:

class Project(models.Model):
    ...
    person_in_project = models.ManyToManyField(User, related_name='project_person', blank=True, through=ProjectPerson)

文档解释了其余的细节,但在这种情况下您不必处理 limit_choices_to。

【讨论】:

  • 这很好。通过 ManyToMany 字段可以为他们的关系添加更多细节。谢谢!
【解决方案2】:

感谢您的帮助,它非常有用。最有帮助的评论是 ryanmrubin 和使用 through 与 ManyToManyField 来促进他们的关系我最终创建了一个单独的类并将其与项目相关联。

如果我需要将更多信息绑定到这个新类中,我肯定会使用 ManyToManyField。

class Project(models.Model):
    project_name = models.CharField(max_length = 120,null = False,blank = False)
    project_percent_complete = models.IntegerField(blank = True,null = True, default = 0)
    project_description = models.CharField(max_length = 300,null = True,blank = True)
    people_in_project = models.ManyToManyField(User,blank = True)

class Project_Tasks(models.Model):
    description = models.CharField(max_length = 120,blank = True)
    percent_complete = models.IntegerField(default = 0)
    user = models.OneToOneField(User,unique = True,blank = True, null = True)
    project = models.OneToOneField(Project,unique = True, blank = False, null = True)

【讨论】:

    猜你喜欢
    • 2010-11-08
    • 1970-01-01
    • 2016-05-13
    • 2010-09-14
    • 2013-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-17
    相关资源
    最近更新 更多