Search code examples
pythondjangodatabasedjango-modelsnameerror

Django models NameERROR in the same file?


good day to everyone, i had the name error in this code, someone can explain me why, please???

category = models.ManyToManyField(Category) NameError: name 'Category' is not defined


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

class Store(models.Model):
    business_name = models.CharField(max_length=100, null=False, verbose_name='Nombre')
    nit = models.PositiveIntegerField(null=False,default=0,verbose_name='NIT')
    category = models.ManyToManyField(Category)
    def __str__(self):
        return self.business_name

    class Meta:
        db_table = 'Store'
        verbose_name = 'Tienda'
        verbose_name_plural = 'Tiendas'
        ordering = ['id']

class Category(models.Model):
    name = models.CharField(max_length=150, verbose_name='Name')

    def __str__(self):
        return self.name
    
    class Meta:
        verbose_name = 'Categoria'
        verbose_name_plural = 'Categorias'
        ordering = ['id']

thanks for your comments


Solution

  • When python is reading the file, it gets to the category = models.ManyToManyField(Category) but doesnt know what Category is yet,

    Move the Category class BEFORE Store, and all will work.