Django ORM - 模型引用另一个模型ManyToMany字段

问题描述 投票:0回答:2

我目前正在尝试在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)是我不知道如何制作。

django orm
2个回答
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)

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字段更改,或在M2M字段上添加或删除through =)

© www.soinside.com 2019 - 2024. All rights reserved.