Django 如何与用户创建 M2M 关系 table

Django How to create M2M relation with User table

我想与用户 table 建立 M2M 关系,但它不起作用。

这是我的代码:

from django.contrib.auth.models import User
# Create your models here.

class projects(models.Model):

    project_name = models.CharField(verbose_name=" ", max_length=250, blank=True, null=True)
    description = models.CharField(verbose_name=" ", max_length=500, blank=True, null=True)
    create_date = models.DateField(verbose_name='', auto_now_add=True, null=True, blank=True,
        help_text="")
    start_date = models.DateField(verbose_name='', null=True, blank=True,
        help_text="")
    end_date   = models.DateField(verbose_name='', null=True, blank=True,help_text="")
    url = models.CharField(max_length=50)
    user = models.ManyToManyField('User')

    def __unicode__(self):
        return u"%s" % (self.project_name)

项目 table 应与用户 table 进行 M2M,但它会导致错误:

django.core.management.base.CommandError: One or more models did not validate:
projects.projects: 'user' has an m2m relation with model User, which has either not been installed or is abstract.

对于这种情况,我应该解决什么问题?

您应该将 auth 应用程序名称添加到 M2M 字段定义中:

user = models.ManyToManyField('auth.User')

或按原样使用 User 模型,不加引号:

user = models.ManyToManyField(User)

要么使用 "auth.User",要么去掉引号并使用您直接导入的用户对象。