NameError: name 'Usuario' is not defined

NameError: name 'Usuario' is not defined

当我尝试做 "makemigrations"

时,我在 django 中遇到了这个错误

代码:

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

# Create your models here.

class Usuario(models.Model):
    user = models.OneToOneField(User)
    amigos = models.ManyToManyField(Amigo)



class Amigo(models.Model):  
    usuarios = models.ForeignKey(Usuario)



class Regalo(models.Model):
    nombre = models.CharField(max_length=100)
    enlace_compra = models.CharField(max_length=200)
    amigo_encargado = models.OneToOneField(User)

对不起,我的英语很差,我用的是翻译。

Amigo class 没有在 Usuario class 声明时定义,所以你不能在 amigos 字段中使用它。

来自 django 文档:

If you need to create a relationship on a model that has not yet been defined, you can use the name of the model, rather than the model object itself

更改 Usuario 中的这一行 class:

amigos = models.ManyToManyField(Amigo)

至:

amigos = models.ManyToManyField('Amigo')