Home > Blockchain >  Do I need to import class on it's own file?
Do I need to import class on it's own file?

Time:08-15

Ok so, I have created 2 model classes for my Django Rest application and am trying to use foreign key to join both models.

Here's my code:

from django.db import models

class Article(models.Model):
    title = models.CharField(max_length=100)
    author = models.ForeignKey(Author, on_delete=models.CASCADE)
    date = models.DateTimeField(auto_now_add=True)



class Author(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField(max_length=100)

The thing is, the Article parameter in the ForeignKey has a "Author" is not defined warning. What am I doing wrong here? Should't the classes in the same file all be "imported" already?

Do I really need to import the class in the same file it is being used?

CodePudding user response:

The classes in .py file are load with order from the begining of file. So one way is to change order of class declaration:

class Author(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField(max_length=100)


class Article(models.Model):
    title = models.CharField(max_length=100)
    author = models.ForeignKey(Author, on_delete=models.CASCADE)
    date = models.DateTimeField(auto_now_add=True)

Or django models allow us to use psedonames (for complicated relations it's not easy to order classes one after another):

class Article(models.Model):
    title = models.CharField(max_length=100)
    author = models.ForeignKey('Author', on_delete=models.CASCADE)
    date = models.DateTimeField(auto_now_add=True)


class Author(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField(max_length=100)

You can remove from . import Author

  • Related