简体   繁体   中英

Unresolved reference to a class in Python

I'm new to Python so don't get irritated please.

I have this issue with Unresolved reference in Python. Here is my code:

from django.db import models

# Create your models here.
from django.db.models import CASCADE


class Post(models.Model):
    author_id = models.ForeignKey(Author, CASCADE)
    title = models.CharField(max_length=50)
    excerpt = models.CharField(max_length=50)
    image_name = models.CharField(max_length=50)
    date = models.DateField()
    slug = models.CharField(max_length=50)
    content = models.TextField()


class Author(models.Model):
    first_name = models.CharField(max_length=10)
    last_name = models.CharField(max_length=10)
    email_address = models.CharField(max_length=50)


class Tag(models.Model):
    caption = models.CharField(max_length=50)

I get Unresolved reference (Author) on the

 author_id = models.ForeignKey(Author, CASCADE)

I kinda realize that it might be a problem with interpreter, but how to solve this? If I'm not mistaken in C++ there is a similar issue, and you solve it by declaring the name in the beginning of a file. How do you do that in Python?

You classes are not in the right order. At the point where Author is used it has not been created so far, because it is further down the code.

Change the order and it should work:

class Author(models.Model):
    first_name = models.CharField(max_length=10)
    last_name = models.CharField(max_length=10)
    email_address = models.CharField(max_length=50)


class Post(models.Model):
    author_id = models.ForeignKey(Author, CASCADE)
    title = models.CharField(max_length=50)
    excerpt = models.CharField(max_length=50)
    image_name = models.CharField(max_length=50)
    date = models.DateField()
    slug = models.CharField(max_length=50)
    content = models.TextField()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM