0

I'm creating the model for my django site (python, if that's not obvious).

from django.db import models

class Picture(models.Model):
        name = models.CharField(max_length=100)
        pub_date = models.DateTimeField('date published')
        tags = models.ManyToManyField(Tag)
        owner = models.ForeignKey(User)

class Tag(models.Model):
        pics = models.ManyToManyField(Picture)
        name = models.CharField(max_length=30)

class User(models.Model):
        name = models.CharField(max_length=20)
        date_joined = models.DateTimeField('date joined')

class Comment(models.Model):
        content = models.CharField(max_length=500)
        date = models.DateTimeField('date commented')
        commenter = models.ForeignKey(User)
        pic = models.ForeignKey(Picture)

That's the entire current model, but I'm getting an error on the line tags = models.ManyToManyField(Tag), saying "NameError: name 'Tag' is not defined"

What's the deal with that?

River Tam
  • 3,096
  • 4
  • 31
  • 51

1 Answers1

1

You declare Tag after you declare Picture, but Picture uses Tag, so it's not defined at the time you try to use it. Just change the order of your classes and it should solve things.

In other words, change your code to:

class Tag(models.Model):
    pics = models.ManyToManyField(Picture)
    name = models.CharField(max_length=30)

# Hurray, Tag exists now

class Picture(models.Model):
    name = models.CharField(max_length=100)
    pub_date = models.DateTimeField('date published')

    # Therefore, this next line will work

    tags = models.ManyToManyField(Tag)
    owner = models.ForeignKey(User)

(minus my comments)

machineghost
  • 33,529
  • 30
  • 159
  • 234
  • I see... if that's true, I also use Picture in my Tag class. How can I resolve this if both are dependent on each other? – River Tam Dec 01 '12 at 00:49
  • 1
    Read this: http://stackoverflow.com/questions/8466726/django-circular-model-reference (the short answer is that you can do `models.ManyToManyField('Tag')` instead, and since Tag will be a string and not a class it should work. – machineghost Dec 01 '12 at 00:52
  • Beautiful! That seemed to work. Haha, I was going to say "Thank God for scripting languages", but I suppose scripting languages caused the problem in the first place... – River Tam Dec 01 '12 at 00:54
  • Heh, well good look finding something as accommodating as Django in a static language like Java or C (I can't remember how Hibernate handles something like thus, but even without remembering I'm pretty sure it's fugly ;-) ) – machineghost Dec 01 '12 at 00:55