Django ORM-引用其他模型ManyToMany字段的模型

时间:2019-04-14 13:35:06

标签: django orm

我目前正在尝试在djangos ORM中设置一些数据库模型。但是我无法弄清楚我应该如何引用多对多字段的另一个模型。

项目模型

class Project(models.Model):
    projectName = models.CharField(max_length=200)
    users = models.ManyToManyField(get_user_model())
    projectOwner = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, related_name='projectowner', default=1)

users = models.manytomanyfield(get_user_mode())工作正常 并在数据库中生成正确的关系。 现在我想添加一个新模型,该模型在权限和project_user之间添加多对多关系 所以最终结果表应该是这样的:

project:
projectname - string
projectowner - id of referenced user

user: django orm auth user model

rights:
name
description
etc

project_user:
id
project_id
user_id

rights_projectuser:
id
rights_id
project_user_id

现在最后一个(rights_projectuser)是我不知道如何制作的。

2 个答案:

答案 0 :(得分:1)

您需要将“ project_user”转换为through model,然后可以将多对多关系添加到其中。

class Project(models.Model):
    projectName = models.CharField(max_length=200)
    users = models.ManyToManyField(get_user_model(), through='ProjectUser')

class ProjectUser(models.Model):
    project = models.ForeignKey(Project, on_delete=models.CASCADE)
    user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
    rights = models.ManyToManyField(Right)

答案 1 :(得分:0)

我现在在运行此代码时遇到以下问题:

from django.db import models
from django.contrib.auth import get_user_model

User = get_user_model()

class Project(models.Model):
    projectName = models.CharField(max_length=200)
    users = models.ManyToManyField(get_user_model(), through='ProjectUser')
    projectOwner = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, related_name='projectowner', default=1)

class Right(models.Model):
    name = models.CharField(max_length=200)
    description = models.CharField(max_length=1000)

class ProjectUser(models.Model):
    user_id = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
    project_id = models.ForeignKey(Project, on_delete=models.CASCADE)
    rights = models.ManyToManyField(Right)

ValueError:无法将字段wspingpong.Project.users更改为wspingpong.Project.users-它们是不兼容的类型(您不能在M2M字段之间更改,也不能在M2M字段上添加或删除through =)