如何订购具有M2M关系的模型以避免NameSpace错误?

时间:2010-02-18 22:11:11

标签: python django django-models

我无法弄清楚我应该如何订购这些具有M2M关系的模型。

当我尝试syncdb时,我不能,因为模型相关模型还没有在命名空间中,所以我得到:

  

NameError:名称'Fav​​oriteQuestion'未定义

如果我换位置,我会:

  

NameError:名称'UserProfile'未定义

class UserProfile(models.Model):  
    """User Profile customizations"""  
    user = models.ForeignKey(User, unique=True)  
    favorite_questions =  models.ManyToManyField(Question, through=FavoriteQuestion,  
                                                 related_name='favorited_by')  
    badges = models.ManyToManyField(Badge, through=Award,  
                                    related_name='awarded_to')  


class FavoriteQuestion(models.Model):  
    """A favorite Question of a User."""  
    question      = models.ForeignKey(Question)  
    user          = models.ForeignKey(UserProfile, related_name='user_favorite_questions')  
    added_at = models.DateTimeField(default=datetime.datetime.now)

这是TraceBack:

$ python manage.py syncdb   
    Traceback (most recent call last):   
      File "manage.py", line 11, in <module>   
        execute_manager(settings)   
      File "/usr/local/lib/python2.6/site-packages/django/core/management/__init__.py", line 439, in execute_manager   
        utility.execute()   
      File "/usr/local/lib/python2.6/site-packages/django/core/management/__init__.py", line 380, in execute   
        self.fetch_command(subcommand).run_from_argv(self.argv)   
      File "/usr/local/lib/python2.6/site-packages/django/core/management/base.py", line 195, in run_from_argv   
        self.execute(*args, **options.__dict__)   
      File "/usr/local/lib/python2.6/site-packages/django/core/management/base.py", line 221, in execute   
        self.validate()   
      File "/usr/local/lib/python2.6/site-packages/django/core/management/base.py", line 249, in validate   
        num_errors = get_validation_errors(s, app)   
      File "/usr/local/lib/python2.6/site-packages/django/core/management/validation.py", line 28, in get_validation_errors   
        for (app_name, error) in get_app_errors().items():   
      File "/usr/local/lib/python2.6/site-packages/django/db/models/loading.py", line 131, in get_app_errors   
        self._populate()   
      File "/usr/local/lib/python2.6/site-packages/django/db/models/loading.py", line 58, in _populate   
        self.load_app(app_name, True)   
      File "/usr/local/lib/python2.6/site-packages/django/db/models/loading.py", line 74, in load_app   
        models = import_module('.models', app_name)   
      File "/usr/local/lib/python2.6/site-packages/django/utils/importlib.py", line 35, in import_module   
        __import__(name)   
      File "/Users/Bryan/work/APPNAME/forum/models.py", line 434, in <module>   
        class FavoriteQuestion(models.Model):   
      File "/Users/Bryan/work/APPNAME/forum/models.py", line 437, in FavoriteQuestion   
        user          = models.ForeignKey(UserProfile, related_name='user_favorite_questions')   
    NameError: name 'UserProfile' is not defined   

2 个答案:

答案 0 :(得分:0)

您无需在UserProfile上创建favourite_question字段。

只要每个FavouriteQuestion都有一个与之关联的用户,模型实例API就可以让您访问用户最喜欢的问题列表。

答案 1 :(得分:0)

不是将Class传递给字段构造函数,而是传入类名的字符串。 Django将负责确定如何连接模型,而不依赖于类定义存在于定义另一个类的模块中。我实际上会为您定义的所有关系执行此操作:

class UserProfile(models.Model):  
    """User Profile customizations"""  
    user = models.ForeignKey('User', unique=True)  
    favorite_questions =  models.ManyToManyField('Question', through='FavoriteQuestion',  
                                                 related_name='favorited_by')  
    badges = models.ManyToManyField('Badge', through='Award',  
                                    related_name='awarded_to')  


class FavoriteQuestion(models.Model):  
    """A favorite Question of a User."""  
    question = models.ForeignKey('Question')
    user = models.ForeignKey('UserProfile', related_name='user_favorite_questions')  
    added_at = models.DateTimeField(default=datetime.datetime.now)