简体   繁体   English

Python - 如何在同一个文件中定义相互依赖的类?

[英]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.

相关问题 在 Python 中,如何获取特定文件中定义的类列表? - In Python, how do I get the list of classes defined within a particular file? 你如何相互依赖处理同一模块中的多个Python类? - How do you deal with multiple Python classes in the same module depending on each other? 如何在Python的同一文件中将类导入其他类 - How to import classes into other classes within the same file in Python Python - 如何在定义其他类之前从其他类获取信息/使用函数? - Python - How to get information/use functions from other classes before I defined them? Python 类与另一个类在同一个文件中定义 - 如何访问文件中稍后定义的类? - Python class defined in the same file as another class - how do you get access to the one defined later in the file? 如何从两个不同文件中的两个不同类中获取函数以相互通信? - How do I get functions from two different classes in two different files to communicate with each other? 使用 python 父类并得到错误 x 未定义我该如何解决这个问题 - using python parent classes and get error x is not defined how do i fix this 相互依赖的模块 - Modules that rely on each other 我如何使班级互相交谈? - How do I make classes talk to each other? 如何让我的代码使用定义的函数验证文件中的每一行 - How do I get my code to validate each line in file using a defined function
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM