【问题标题】:Django models ManyToMany relations mechanicsDjango 建模多对多关系机制
【发布时间】:2017-11-10 18:46:02
【问题描述】:

我需要创建 Profile 模型和 Project 模型,并不真正了解 ManyToMany 字段机制。

现在我得到了:

class Project(models.Model):
    title = models.CharField(max_length=20, unique=True)
    ...

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, unique=True)
    projects = models.ManyToManyField(Project, related_name='profiles')
    ...

我现在可以使用 project.profiles 调用与项目相关的所有配置文件吗?如何将配置文件字段添加到项目管理表单中?我试图找到一些示例,但没有找到任何示例。

【问题讨论】:

    标签: python django python-3.x django-models django-forms


    【解决方案1】:

    您可以从一个项目中获取所有配置文件,执行类似的操作:

    # Setup
    project1 = Project.objects.get(title='first')
    project2 = Project.objects.get(title='second')
    
    profile = Profile.objects.create(user=user)
    profile.projects.add(project2)
    
    # Get all profiles from a project
    project2.profiles.all()
    >>> <QuerySet [<Profile: Profile object>]>
    

    关于表单,我不适合回答这个问题,因为我不使用,我更喜欢使用“原始”表单。

    【讨论】:

    • 最后,我使用了“原始”表单,票已关闭,谢谢 c:
    猜你喜欢
    • 1970-01-01
    • 2019-05-09
    • 1970-01-01
    • 2020-09-28
    • 1970-01-01
    • 2018-01-04
    • 2012-07-22
    • 2015-02-03
    • 2017-08-25
    相关资源
    最近更新 更多