[英]Python - How do I get classes that rely on each other to be defined in the same file?
I have the following code used in Django:我在 Django 中使用了以下代码:
from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class User(AbstractUser):
groups = models.ManyToManyField(group)
class group(models.Model):
owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="course", null=True)
name = models.CharField(max_length=50)
description = models.CharField(max_length=300)
def __str__(self):
return self.name
I made this code to get a user model in django that allows for more fields.我编写此代码是为了在 django 中获取允许更多字段的用户 model。 However, the new user class requires the group field since a user can join many groups.但是,新用户 class 需要组字段,因为用户可以加入许多组。 This is causing an error since the group is defined after class.这会导致错误,因为该组是在 class 之后定义的。 What do I do to fix this issue?我该怎么做才能解决这个问题? What I really need is just a way to add extra fields to the default User class so I tried it like so from another SE post.我真正需要的只是一种向默认用户 class 添加额外字段的方法,所以我从另一个 SE 帖子中尝试过。
You can to put quotes around the word "group" in the definition of the User model field:您可以在 User model 字段的定义中为单词“group”加上引号:
class User(AbstractUser):
groups = models.ManyToManyField('group')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.