我需要创建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调用与项目连接的所有配置文件,以及如何将配置文件字段添加到项目管理表单中吗?我试图找到一些例子但没找到任何例子。
答案 0 :(得分:0)
您可以从项目中获取类似的所有配置文件:
# 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>]>
关于表单,我不是最好的回答,因为我不使用,我更喜欢使用&#34; raw&#34;形式。